Accumulating values in dictionary
Arnaud Delobelle
arnodel at googlemail.com
Tue May 20 13:12:14 EDT 2008
Zack <zhalbrecht at gmail.com> writes:
> 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
This is fine. If I wrote this, I'd write it like this:
d = {}
for person in people:
fav_food = person.fav_food
if fav_food in d:
d[fav_food] += 1
else:
d[fav_food] = 1
You can use d.get() instead:
d = {}
for person in people:
fav_food = person.fav_food
d[fav_food] = d.get(fav_food, 0) + 1
Or you can use a defaultdict:
from collections import defaultdict
d = defaultdict(int) # That means the default value will be 0
for person in people:
d[person.fav_food] += 1
HTH
--
Arnaud
More information about the Python-list
mailing list