Accumulating values in dictionary

Thomas Bellman bellman at lysator.liu.se
Tue May 20 09:56:02 EDT 2008


Zack <zhalbrecht at gmail.com> wrote:

> 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.)


-- 
Thomas Bellman,   Lysator Computer Club,   Linköping University,  Sweden
"If you ignore performance problems long enough, they   !    bellman @
 somehow seem to go away."          -- Barry A Warsaw   ! lysator.liu.se



More information about the Python-list mailing list