Append a new value to dict

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Wed Oct 22 17:12:57 EDT 2008


On Wed, 22 Oct 2008 10:12:56 -0700, bearophileHUGS wrote:

> 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

Or:

counter['B'] = counter.get('B', 0) + 1

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list