Search code examples
pythonlogic

How to extract value from tuple of tuples


I have list of this sort. It is the order list of a person:

orderList  = [('apples', 2.0), ('pears', 3.0), ('limes', 4.0)]
#Here the second value is the quantity of the fruit to be purchased

How do I extract the string and the float value separately? I need to calculate the total order cost based on the given fruit prices:

fruitPrices = {'apples':2.00, 'oranges': 1.50, 'pears': 1.75,
              'limes':0.75, 'strawberries':1.00}

This is what I have tried:

def buyLotsOfFruit(orderList):
    """
        orderList: List of (fruit, numPounds) tuples

    Returns cost of order
    """
    totalCost = 0.0
    length = len(orderList)
    for i in range(0,length):
        for j in range(0, length - i - 1):
            totalCost += fruitPrices[orderList[i]] * orderList[j]
    return totalCost

This yields wrong answer. What am I doing wrong? How can I fix this?

Thanks!


Solution

  • You might use unpacking together with for loop to get easy to read code, for example

    orderList  = [('apples', 2.0), ('pears', 3.0), ('limes', 4.0)]
    fruitPrices = {'apples':2.00, 'oranges': 1.50, 'pears': 1.75,
                  'limes':0.75, 'strawberries':1.00}
    total = 0.0
    for name, qty in orderList:
        total += qty * fruitPrices[name]
    print(total)  # 12.25
    

    Note , inside for...in so name values become 1st element of tuple and qty becomes 2nd element of tuple.