Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python List of Dictionaries[int : tuple] Sum [duplicate]

Tags:

python

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

like image 219
Pavan Avatar asked Jul 25 '13 15:07

Pavan


People also ask

Can list and tuple have duplicate values?

Tuple is a collection which is ordered and unchangeable. Allows duplicate members.

How do you sum a dictionary in a list?

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.

Is duplication allowed in tuple?

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.

Can dictionaries contain duplicate values in Python?

Dictionaries in Python First, a given key can appear in a dictionary only once. Duplicate keys are not allowed.


1 Answers

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
like image 98
Martijn Pieters Avatar answered Nov 15 '22 12:11

Martijn Pieters