Accumulating values in dictionary

Thomas Bellman bellman at lysator.liu.se
Tue May 20 10:38:01 EDT 2008


Arnaud Delobelle <arnodel at googlemail.com> wrote:

> from collections import defaultdict
> d = defaultdict(int) # That means the default value will be 0
> for person in people:
>     d[person.fav_food] += 1

Ah!  I didn't think of using int as the factory function.  If you
use this, then I believe the warning I gave about performance
does not apply; my understanding is that calling built-in functions
(like the int constructor) is fast.


-- 
Thomas Bellman,   Lysator Computer Club,   Linköping University,  Sweden
"Beware of bugs in the above code; I have    !  bellman @ lysator.liu.se
 only proved it correct, not tried it."      !  Make Love -- Nicht Wahr!



More information about the Python-list mailing list