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 Python 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 values. 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.
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) print(myDict)
You can see from the below output, it is displaying 100 for all the keys.
{'c': 100, 'b': 100, 'd': 100, 'a': 100, 'e': 100}