tags:

views:

107

answers:

4

last one for the night, want to see what clever ways there are with python to add all of the 'count' values from the following type of dictionary:

{0: {'count': 1000}, 1: {'count': 2000}}

so the end result should be an int value of 3000.

A: 
sum(i['count'] for i in d.values())
Ken
+4  A: 
>>> x = {0: {'count': 1000}, 1: {'count': 2000}}
>>> sum(v['count'] for v in x.values()) 
3000
Ned Deily
Use .itervalues() to save some memory overhead, since .values() builds a new list for the values.
Matt Good
+4  A: 

A shorter one:

sum(d[k]['count'] for k in d)
dF
It saves a few characters, but it's slower since you have to look up each key, instead of iterating over the values directly.
Matt Good
Well technically, for the example it's 5% faster :) But you're right, for large dicts it's about 15% slower.
dF
A: 

How about using reduction in python?

reduce(lambda x,y: x+y, [v['count'] for v in a.values()])
Raymond Tay