Search code examples
pythontuplesswap

how to find the sum in a nested tuple


Write a python program to define a tuple to accept 3 food product details such as Products name with their Price and Expiry date in a sub tuple, then find the sum of price of all products which are having same expiry date.

t=(('CAKE', (748.0, '07-09-2020')), ('JELLY', (12.0, '07-09-2020')), ('CREAM', (244.0, '03-11-2020')))

Then, the output should be like

TOTAL PRICE:760
t=(('CAKE', (748.0, '07-09-2020')), ('JELLY', (12.0, '07-09-2020')), ('CREAM', (244.0, '03-11-2020')))
l=list(t);total=0
for i in range(0,len(l)):
    check=l[i][1][1]
    c=l.count(check)
    if c>1:
        total+=l[i][1][0]
print(total)

How to solve ??


Solution

  • You have another answer already based on defaultdict, but I'm adding another one in order to show also how each of the data items can be unpacked directly into the relevant variables (price and date). The _ here is a variable which will contain the description (e.g. 'CAKE') but because we are not using the value here, I am using the conventional name for a dummy variable instead of calling it name or whatever.

    Using defaultdict(float), the elements of the dictionary are created automatically as floating point zeros when they are first referenced.

    from collections import defaultdict
    
    t = (('CAKE', (748.0, '07-09-2020')),
         ('JELLY', (12.0, '07-09-2020')),
         ('CREAM', (244.0, '03-11-2020')))
    
    totals = defaultdict(float)
    for _, (price, date) in t:
        totals[date] += price
    
    for date in totals:
        print(f'{date} {totals[date]}')
    

    Gives:

    07-09-2020 760.0
    03-11-2020 244.0
    

    Note that depending on your python version, the order of dates in the output might vary.


    Update: you also asked how it can be done without using defaultdict -- like this:

    totals = {}
    for _, (price, date) in t:
        if date not in totals:
            totals[date] = 0.
        totals[date] += price