Accumulating values in dictionary

Zack zhalbrecht at gmail.com
Tue May 20 12:57:26 EDT 2008


On May 20, 12:26 pm, Zack <zhalbre... at gmail.com> wrote:
> Given a bunch of objects that all have a certain property, I'd like to
> accumulate the totals of how many of the objects property is a certain
> value. Here's a more intelligible example:
>
> Users all have one favorite food. Let's create a dictionary of
> favorite foods as the keys and how many people have that food as their
> favorite as the value.
>
> d = {}
> for person in People:
>     fav_food = person.fav_food
>     if d.has_key(fav_food):
>         d[fav_food] = d[fav_food] + 1
>     else:
>         d[fav_food] = 1
>
> d ends up being something like: {'pie': 400, 'pizza': 200, 'burgers':
> 100} if 400 people like pie, 200 like pizza and 100 like burgers.
>
> There's nothing wrong (that I know of) by doing it as I have up there,
> but is there a simpler, easier way? Looking forward to hearing about
> how much of a n00b I am. Thanks in advance!

Er. OK so I realize now that I could have just done this:

d = {}
for person in people:
    fav_food = person.fav_food
    d[fav_food] = d.get(fav_food, 0) + 1




More information about the Python-list mailing list