Append a new value to dict

pruebauno at latinmail.com pruebauno at latinmail.com
Mon Oct 13 11:12:31 EDT 2008


On Oct 13, 9:41 am, Marc 'BlackJack' Rintsch <bj_... at gmx.net> wrote:
> 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

...and if you are using Python 2.5 or later you can use the
collections module with collections.defaultdict(list) or
collections.defaultdict(int) to do the same thing. I personally find
it easier to read.



More information about the Python-list mailing list