On Oct 13, 9:41 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> 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. -- http://mail.python.org/mailman/listinfo/python-list