views:

103

answers:

4

I'd like to get, from:

keys = [1,2,3,4]

this:

{1: None, 2: None, 3: None}

A pythonic way of doing it?

This is an ugly one:

>>> keys = [1,2,3]
>>> dict([(1,2)])
{1: 2}
>>> dict(zip(keys, [None]*len(keys)))
{1: None, 2: None, 3: None}
+12  A: 

dict.fromkeys([1, 2, 3, 4])

This is actually a classmethod, so it works for dict-subclasses (like collections.defaultdict) as well. The optional second argument specifies the value to use for the keys (defaults to None.)

Thomas Wouters
+1: And I learned something new. :)
Mark Byers
+4  A: 
dict.fromkeys(keys, None)
Dominic Cooney
A: 
d = {}
for i in list:
    d[i] = None
inspectorG4dget
A: 

nobody cared to give a dict-comprehension solution ?

>>> keys = [1,2,3,5,6,7]
>>> {key: None for key in keys}
{1: None, 2: None, 3: None, 5: None, 6: None, 7: None}
Adrien Plisson
This only works in Python 3.x
Juanjo Conti