Dictionaries and incrementing keys

AlienBaby matt.j.warren at gmail.com
Tue Jun 14 08:37:45 EDT 2011


On Jun 14, 12:16 pm, Peter Otten <__pete... at web.de> wrote:
> 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.defaultdicthttp://docs.python.org/library/collections.html#collections.Counter



How do those methods compare to the one I normally use;

try:
 dict[key]+=1
except:
 dict[key]=1




More information about the Python-list mailing list