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}
This question is related to
dictionary
python
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
.)
default_keys = [1, "name"]
To get dictionary with None as values:
dict.fromkeys(default_keys)
Output :
{1: None, 'name': None}
To get dictionary with default values:
dict.fromkeys(default_keys, [])
Output :
{1: [], 'name': []}
dict.fromkeys(keys, None)
You could use dict.fromkeys as follows:
dict.fromkeys([1, 2, 3, 4], list())
This will create a list object for each key. If you change value for any specific key it won't affect other keys (as most people would want, I presume).
d = {}
for i in keys:
d[i] = None
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}
>>> keyDict = {"a","b","c","d"}
>>> dict([(key, []) for key in keyDict])
Output:
{'a': [], 'c': [], 'b': [], 'd': []}
In many workflows where you want to attach a default / initial value for arbitrary keys, you don't need to hash each key individually ahead of time. You can use collections.defaultdict
. For example:
from collections import defaultdict
d = defaultdict(lambda: None)
print(d[1]) # None
print(d[2]) # None
print(d[3]) # None
This is more efficient, it saves having to hash all your keys at instantiation. Moreover, defaultdict
is a subclass of dict
, so there's usually no need to convert back to a regular dictionary.
For workflows where you require controls on permissible keys, you can use dict.fromkeys
as per the accepted answer:
d = dict.fromkeys([1, 2, 3, 4])
Source: Stackoverflow.com