dict initialization

Mark Tolonen metolone+gmane at gmail.com
Tue Dec 22 17:02:56 EST 2009


"mattia" <gervaz at gmail.com> wrote in message 
news:4b313b3a$0$1135$4fafbaef at reader1.news.tin.it...
> 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?

Depending on your use case, a defaultdict might suite you:

>>> from collections import defaultdict
>>> D=defaultdict(list)
>>> D[0]
[]
>>> D[49]
[]

If the key doesn't exist, it will be initialized by calling the factory 
function provided in the constructor.

-Mark





More information about the Python-list mailing list