I’d like to get from this:
keys = [1,2,3]
to this:
{1: None, 2: None, 3: None}
Is there a pythonic way of doing it?
This is an ugly way to do it:
>>> keys = [1,2,3]
>>> dict([(1,2)])
{1: 2}
>>> dict(zip(keys, [None]*len(keys)))
{1: None, 2: None, 3: None}
dict.fromkeysdirectly solves the problem:This is actually a classmethod, so it works for dict-subclasses (like
collections.defaultdict) as well.The optional second argument, which defaults to
None, specifies the value to use for the keys. Note that the same object will be used for each key, which can cause problems with mutable values:If this is unacceptable, see How can I initialize a dictionary whose values are distinct empty lists? for a workaround.