Dictionaries and incrementing keys

Raymond Hettinger python at rcn.com
Sat Jun 25 04:13:27 EDT 2011


On Jun 14, 12:57 pm, Steve Crook <st... at mixmin.net> wrote:
> Today I spotted an alternative:
>
> dict[key] = dict.get(key, 0) + 1
>
> Whilst certainly more compact, I'd be interested in views on how
> pythonesque this method is.

It is very pythonesque in the it was the traditional one way to do it
(also one of the fastest ways).

Now we have collections.Counter which simplifies the code to:

   c = Counter()
   ...
   c[key] += 1

For existing keys, it is as fast as a regular dictionary (because it
is a dict subclass and it does not override or extend either
__getitem__ or __setitem__).  For new keys, it is a little slower
because it calls the __missing__ method which returns zero.

Raymond




More information about the Python-list mailing list