Python Dictionary fromkeys

Python fromkeys function is used to create a new dictionary using user given key sequence, and value. In this section, we discuss how to use this fromkeys function with practical examples.

The syntax of this Dictionary fromkeys function is:

dictionary_name.fromkeys(sequence, values)

By default, Values (second argument) = None. But, you can define as per your requirement.

Python Dictionary fromkeys Example

The fromkeys function creates a new dictionary using the user-given sequences and value. In this program, we are creating a dict using a few keys.

TIP: Please refer to the Dict article to understand everything about them in Python.

keys = {'a', 'b', 'c', 'd', 'e'}

myDict = dict.fromkeys(keys)
print("Dictionary Items: ", myDict)

As you can see, all the values returned as None.

Python Dictionary fromkeys Example 1

In this program, we are using the second argument to assign a default value to the given sequence.

keys = {'a', 'b', 'c', 'd', 'e'}
values = 100

myDict = dict.fromkeys(keys, values)

You can see from below output, it is displaying 100 for all the keys.

{'c': 100, 'b': 100, 'd': 100, 'a': 100, 'e': 100}