Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a dict with keys from a list and empty value in Python?

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} 
like image 841
Juanjo Conti Avatar asked Feb 11 '10 02:02

Juanjo Conti


People also ask

How do you create a dictionary with keys but empty values?

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 do you initialize an empty dictionary in Python?

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.

How do you create an empty dictionary in a list?

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: []} .


2 Answers

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.)

like image 189
Thomas Wouters Avatar answered Oct 26 '22 12:10

Thomas Wouters


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} 
like image 30
Adrien Plisson Avatar answered Oct 26 '22 12:10

Adrien Plisson