Python Dictionary fromkeys()
Python Dictionary fromkeys(keys[, value])
method returns a dictionary created with the specified keys and default value.
In this tutorial, we will learn the syntax of dict.fromkeys() method and go through examples covering different scenarios for the arguments that we pass to fromkeys() method.
Syntax
The syntax of dict.fromkeys() is
dict. fromkeys(keys[, value])
where
- keys is an iterable representing the keys of the dictionary we create.
- value is an optional value which is used as a default value for all the specified keys.
Example 1 – Python dict.fromkeys(keys)
In this example, we will pass a list of keys to fromkeys() method. The method returns a dictionary created using the given keys.
If no default value is specified, then None
is set as value for all the keys.
Python Program
keys = ['apple', 'banana', 'cherry']
myDictionary = dict.fromkeys(keys)
print(myDictionary)
Program Output
{'apple': None, 'banana': None, 'cherry': None}
Example 2 – Python dict.fromkeys(keys, value)
In this example, we will pass a list of keys to fromkeys() method, and specify a value of 25
for the keys. The method returns a dictionary created using the given keys and default value.
Python Program
keys = ['apple', 'banana', 'cherry']
myDictionary = dict.fromkeys(keys, 25)
print(myDictionary)
Program Output
{'apple': 25, 'banana': 25, 'cherry': 25}
Conclusion
In this Python Tutorial, we learned about Python Dictionary method dict.fromkeys(). We have gone through the syntax of fromkeys(), and its usage with example programs.