part_1 = {'Ingredient':'Water', 'Amount wt':40 }
part_2 = {'Ingredient':'Dye', 'Amount wt': 50 }
part_3 = {'Ingredient':'Salt', 'Amount wt':10 }
total_mix = {'index 1': part_1,
'index 2': part_2,
'index 3': part_3}
print(total_mix)
I have a dictionary that contains another dictionary like the example above. How can I easily sum up the wt of the total mix?
I have tried making a list like:
mix_list = (total_mix['index 1']['Amount wt'], total_mix['index 2']['Amount wt'], total_mix['index 3']['Amount wt'])
And then using sum() to add them all up and it does work, but I want to know if there is an easier/shorter way to do this. Especially since it feels like it will be very time consuming if there was more items in the dictionaries. Also the dictionary has to be able to call the info with the index numbers, which is why I put it into another dictionary to begin with.
CodePudding user response:
You can use a for loop to iterate over the items in total_mix
and add the values of the Amount wt
key for each inner dictionary.
total_wt = 0
for part in total_mix.values():
total_wt = part['Amount wt']
print("Total weight:", total_wt)
Another solution
total_wt = sum(part['Amount wt'] for part in total_mix.values())
print("Total weight:", total_wt)
Output
Total weight: 100
CodePudding user response:
Previous one-line works perfectly, here is simple for-loop, which you could try as well:
It's not fancy, but it serves the purpose. (for beginner too)
total = 0
for _, v in total_mix.items():
#amt = v.get('Amount wt')
total = v.get('Amount wt') # dv.get(...) just syntax sugar
here
# or this way
#total = dv['Amount wt'] # Edit based on comments
print(total)
# 100
CodePudding user response:
Here it is in a one-liner:
print(sum(part["Amount wt"] for part in total_mix.values()))
This uses total_mix.values()
to get the individual part dictionaries, and uses a generator expression to get the "Amount wt" value in each dictionary. As sum() accepts an iterable, and generator expressions are iterables, we can pass the generator expression to it directly and it will sum up the "Amount wt" values for us.