Python create empty dictionary with keys | Example code

  • by

Use dict.fromkeys() to create an empty dictionary with keys to an empty value in Python.

dict.fromkeys(keys)

Example create an empty dictionary with keys in Python

Simple example code.

keys = ["A", "B", "C", "D"]

d = dict.fromkeys(keys)

print(d)

Output:

Python create empty dictionary with keys

Another example By iterating through the list

keys = ["A", "B", "C", "D"]

# initialize dictionary
d = {}

# iterating through the elements of list
for i in keys:
    d[i] = None

print(d)

Output: {‘A’: None, ‘B’: None, ‘C’: None, ‘D’: None}

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

keys = [1,2,3]

You can use the dict fromkeys method or dict-comprehension to initialize a dict with keys from a list and empty value.

keys = [1, 2, 3]

print(dict.fromkeys(keys))

OR

keys = [1, 2, 3]

res = {key: None for key in keys}
print(res)

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

Do comment if you have any doubts and suggestions on this Python dict tutorial.

Note: IDE: PyCharm 2021.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.