Menu Close

Python Dictionary fromkeys Method

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 have 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.

Python Dictionary fromkeys Method

fromkeys function in Python is a dictionary built-in function, that is used to create the new dictionary with specified keys and specified value.

Syntax

The syntax of 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 new created dictionary.

Python dictionary fromkeys examples

Example:

Create 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 happen, if the value not provoded.

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 tutorial.

For Reference:- Click Here

Previous Article
Next Article

Related Posts

Leave a Reply