building a dict

Jon Clements joncle at
Sat Mar 13 16:25:45 CET 2010

On 13 Mar, 15:05, vsoler < at> wrote:
> Say that "m" is a tuple of 2-tuples
> m=(('as',3), ('ab',5), (None, 1), ('as',None), ('as',6))
> and I need to build a "d" dict where each key has an associated list
> whose first element is the count, and the second is the sum. If a 2-
> tuple contains a None value, it should be discarded.
> The expected result is:
> d={'as':[2, 9], 'ab': [1,5]}
> How should I proceed? So far I have been unsuccessful. I have tried
> with a "for" loop.
> Thank you for your help

Something like:

d = defaultdict( lambda: [0,0] )
for key, val in filter(lambda L: not any(i is None for i in L), m):
    d[key][0] += 1
    d[key][1] += val



More information about the Python-list mailing list