Python Dictionary List [int: tuple] Amount

I have a list of dictionaries. Each dictionary has an integer key and a tuple value. I would like to summarize all the elements located in a specific place in the tuple.

Example:

myList = [{1000:("a",10)},{1001:("b",20)},{1003:("c",30)},{1000:("d",40)}] 

I know I can 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 to do this? Thanks

+7
python
source share
3 answers

Use the generator expression, sorting through all the dictionaries, and then their values:

 sum(v[1] for d in myList for v in d.itervalues()) 

For Python 3, replace d.itervalues() with d.values() .

Demo:

 >>> sum(v[1] for d in myList for v in d.itervalues()) 100 
+7
source share
 import itertools sum((v[1][1] for v in itertools.chain(*[d.items() for d in myList]))) 

itertools can "merge" multiple lists so that they are logically one.

0
source share

I don't know if this is a more pythonic way:

 print sum([i[i.keys()[0]][1] for i in myList]) 
0
source share

All Articles