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}
In Python, we can use the zip() and len() methods to create an empty dictionary with keys. This method creates a dictionary of keys but returns no values from the dictionary.
How to Create An Empty Dictionary in Python. To create an empty dictionary, first create a variable name which will be the name of the dictionary. Then, assign the variable to an empty set of curly braces, {} . Another way of creating an empty dictionary is to use the dict() function without passing any arguments.
To initialize a dictionary of empty lists in Python, we can use dictionary comprehension. to create a dictionary with 2 entries that are both set to empty lists as values. Therefore, data is {0: [], 1: []} .
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
.)
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With