On Jun 14, 12:57 pm, Steve Crook <st...@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

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to