I have a list of dictionaries. Each Dictionary has an integer key and tuple value. I would like to sum all the elements located at a certain position of the tuple.
Example:
myList = [{1000:("a",10)},{1001:("b",20)},{1003:("c",30)},{1000:("d",40)}]
I know i could do something like :
sum = 0
for i in myList:
for i in myList:
temp = i.keys()
sum += i[temp[0]][1]
print sum
Is there a more pythonic way of doing this ? Thanks
Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
To sum the values in a list of dictionaries: Use a generator expression to iterate over the list. On each iteration, access the current dictionary at the specific key. Pass the generator expression to the sum() function.
Tuples A Tuple represents a collection of objects that are ordered and immutable (cannot be modified). Tuples allow duplicate members and are indexed. Lists Lists hold a collection of objects that are ordered and mutable (changeable), they are indexed and allow duplicate members.
Dictionaries in Python First, a given key can appear in a dictionary only once. Duplicate keys are not allowed.
Use a generator expression, looping over all the dictionaries then their values:
sum(v[1] for d in myList for v in d.itervalues())
For Python 3, substitute d.itervalues()
with d.values()
.
Demo:
>>> sum(v[1] for d in myList for v in d.itervalues())
100
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With