dict initialization

Emile van Sebille emile at fenx.com
Tue Dec 22 16:44:00 EST 2009


On 12/22/2009 1:33 PM mattia said...
> 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?

I tend to use setdefault and fill in as I go, but if you need to have a 
complete 50-element dict from the get go, I'd probably do the same.

 >>> D = {}
 >>>
 >>> import random
 >>> for ii in range(20):
...   L=D.setdefault(random.randint(0,9),[])
...   L.append('.')

Emile




More information about the Python-list mailing list