In this dictionary method guide, we are going to learn all about the Python dictionary fromkeys method to create the dictionary.
dictionary fromkeys method returns a created dictionary. In the previous tutorial, we learned the python dictionary copy() method to create a copy of the existing dictionary.
To understand this method, you should have basic knowledge of the Python dictionary.
Headings of Contents
Python Dictionary fromkeys Method
fromkeys function in Python is a dictionary built-in function, that is used to create a new dictionary with specified keys and specified values.
Syntax
The syntax of the python dictionary fromkeys method is:-
dictionary.fromkeys(keys, value)
Parameters
Dictionary fromkeys function in Python accepts two parameters.
- keys:- Required, An Iterable that represents the keys of the new dictionary.
- value:- Value of all the keys. The default value is None.
Return Value
fromkeys method in Python return newly created dictionary.
Python dictionary fromkeys examples
Example:
Create a new dictionary with four keys.
x = ('1st', '2nd', '3rd', '4th')
y = 120
result = dict.fromkeys(x, y)
print(result)
Output
{'1st': 120, '2nd': 120, '3rd': 120, '4th': 120}
Example:
let’s see what happens if the value is not provided.
x = ('1st', '2nd', '3rd', '4th')
result = dict.fromkeys(x)
print(result)
Output
{'1st': None, '2nd': None, '3rd': None, '4th': None}
Conclusion
In this guide, you have seen all about the dictionary fromkeys method to create the new python dictionary. If this article helped you, please continue visiting for further interesting python tutorials.
For Reference:- Click Here