dict initialization

Jon Clements joncle at googlemail.com
Tue Dec 22 19:10:09 EST 2009


On Dec 22, 11:51 pm, mattia <ger... at gmail.com> wrote:
> Il Tue, 22 Dec 2009 23:09:04 +0100, Peter Otten ha scritto:
>
> > mattia wrote:
>
> >> Is there a function to initialize a dictionary? Right now I'm using:
> >> d = {x+1:[] for x in range(50)}
> >> Is there any better solution?
>
> > There is a dictionary variant that you don't have to initialize:
>
> > from collections import defaultdict
> > d = defaultdict(list)
>
> > Peter
>
> ...and it's also the only way to do something like:>>> def zero():
>
> ...     return 0
> ...>>> d = defaultdict(zero)
> >>> s = ['one', 'two', 'three', 'four', 'two', 'two', 'one']
> >>> for x in s:
>
> ...     d[x] += 1
> ...>>> d
>
> defaultdict(<function zero at 0x00BA01E0>, {'four': 1, 'three': 1, 'two':
> 3, 'one': 2
>
> })
>
>

Normally you'd write this defaultdict(int) as int() returns 0 by
default.

Although IIRC, the 3.1 series has a "Counter" class in collections.

Jon.



More information about the Python-list mailing list