Python List of Dictionaries[int : tuple] Sum -


this question has answer here:

i have list of dictionaries. each dictionary has integer key , tuple value. sum elements located @ position of tuple.

example:

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

i know :

sum = 0 in mylist:     in mylist:         temp = i.keys()         sum += i[temp[0]][1] print sum 

is there more pythonic way of doing ? thanks

use generator expression, looping on dictionaries values:

sum(v[1] d in mylist v in d.itervalues()) 

for python 3, substitute d.itervalues() d.values().

demo:

>>> sum(v[1] d in mylist v in d.itervalues()) 100 

Comments

Popular posts from this blog

curl - PHP fsockopen help required -

HTTP/1.0 407 Proxy Authentication Required PHP -

c# - Resource not found error -