Append a new value to dict

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Wed Oct 22 13:12:56 EDT 2008


Frank Niemeyer:
> There's simply no
> way to increment a non-existent value - not without performing some
> obscure implict behind-the-scenes stuff.

Like importing and using a defaultdict(int).


> > So you
> > either have to use a workaround:
>
> >  >>> try:
> > ...   counter['B'] += 1
> > ... except KeyError:
> > ...   counter['B'] = 1
>
> Or you could simply use
>
> if counter.has_key('B'):
>     counter['B'] += 1
> else:
>     counter['B'] = 1

Both those are slow. Better to use:

if 'B' in counter:
    counter['B'] += 1
else:
    counter['B'] = 1

Or with a defaultdict:

counter = defauldict(int)
counter['B'] += 1

Bye,
bearophile



More information about the Python-list mailing list