T
Thomas Bellman
Zack said: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!
You want the defaultdict type:
import collections
d = collections.defaultdict(lambda: 0)
for person in People:
fav_food = person.fav_food
d[fav_food] += 1
New in Python 2.5, so if you require older Python versions, you
can't use that. Note also that this can become slow if most keys
are unique; the function given to defaultdict will be called the
first time a key is mentioned, and if the keys are mostly unique,
that will be the majority of the times, and calling a pure Python
function is fairly slow in CPython. (It probably won't matter
unless you have many thousands of unique keys, though.)