Python Dictionary fromkeys

Python fromkeys Dictionary is one of a Dictionary function used to create a new dictionary using user given key sequence, and value. In this section, we discuss how to use this Dictionary 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 dictionary function creates a new dictionary using the user given sequences and value. In this program, we are creating a dictionary using a few keys.

TIP: Please refer to the Dictionary article to understand everything about Python Dictionaries.

# Python Dictionary fromkeys Example

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

Dictionary fromkeys Example 2

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

# Python Dictionary fromkeys Example

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

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

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

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