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}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can use fromkeys:
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.)
Method 2
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}
Method 3
dict.fromkeys(keys, None)
Method 4
>>> keyDict = {"a","b","c","d"}
>>> dict([(key, []) for key in keyDict])
Output:
{'a': [], 'c': [], 'b': [], 'd': []}
Method 5
d = {}
for i in keys:
d[i] = None
Method 6
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])
Method 7
Just because it’s fun how the dict constructor works nicely with zip, you can repeat the default value and zip it to the keys:
from itertools import repeat
keys = [1, 2, 3]
default_value = None
d = dict(zip(keys, repeat(default_value)))
print(d)
Will give:
{1: None, 2: None, 3: None}
repeat creates an infinite iterator of the element passed to it but as zip stops on the shortest iterable all works well.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0