Coder Perfect

In Python, how do you create a dict with keys from a list and an empty value?

Problem

This is what I’d like to get out of it:

keys = [1,2,3]

to this:

{1: None, 2: None, 3: None}

Is there a way to do it in Python?

This is a dreadful way to go about it:

>>> keys = [1,2,3]
>>> dict([(1,2)])
{1: 2}
>>> dict(zip(keys, [None]*len(keys)))
{1: None, 2: None, 3: None}

Asked by Juanjo Conti

Solution #1

dict.fromkeys is a function that converts a list of keys into ([1, 2, 3, 4])

Because this is a classmethod, it also works for dict-subclasses (such as collections.defaultdict). The second argument, which is optional, gives the value to use for the keys (defaults to None.)

Answered by Thomas Wouters

Solution #2

Nobody was interested in giving 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}

Answered by Adrien Plisson

Solution #3

dict.fromkeys(keys, None)

Answered by Dominic Cooney

Solution #4

>>> keyDict = {"a","b","c","d"}

>>> dict([(key, []) for key in keyDict])

Output:

{'a': [], 'c': [], 'b': [], 'd': []}

Answered by Mayur Koshti

Solution #5

d = {}
for i in keys:
    d[i] = None

Answered by inspectorG4dget

Post is based on https://stackoverflow.com/questions/2241891/how-to-initialize-a-dict-with-keys-from-a-list-and-empty-value-in-python