Append a new value to dict
Marc 'BlackJack' Rintsch
bj_666 at gmx.net
Mon Oct 13 09:41:11 EDT 2008
On Mon, 13 Oct 2008 14:10:43 +0200, Mathias Frey wrote:
> However incrementing a non-existing key throws an exception. So you
> either have to use a workaround:
>
> >>> try:
> ... counter['B'] += 1
> ... except KeyError:
> ... counter['B'] = 1
>
> Since this looks ugly somebody invented the setdefault method:
>
> >>> counter['B'] = counter.setdefault('B',0) + 1
Nope, for this use case there is the `dict.get()` method:
counter['B'] = counter.get('B', 0) + 1
This assigns only *once* to ``counter['B']`` in every case.
`dict.setdefault()` is for situations where you really want to actually
put the initial value into the dictionary, like with the list example by
the OP.
Ciao,
Marc 'BlackJack' Rintsch
More information about the Python-list
mailing list