Zack <[EMAIL PROTECTED]> 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 -- http://mail.python.org/mailman/listinfo/python-list