Dictionaries and incrementing keys
Peter Otten
__peter__ at web.de
Tue Jun 14 07:16:47 EDT 2011
Steve Crook wrote:
> I've always done key creation/incrementation using:
>
> if key in dict:
> dict[key] += 1
> else:
> dict[key] = 1
Your way is usually faster than
> dict[key] = dict.get(key, 0) + 1
>
> Whilst certainly more compact, I'd be interested in views on how
> pythonesque this method is.
You may also consider
http://docs.python.org/library/collections.html#collections.defaultdict
http://docs.python.org/library/collections.html#collections.Counter
More information about the Python-list
mailing list