How does fromkeys() work in Python?

The in-built fromkeys() method in Python is used to return a new dictionary.

Syntax

dict.fromkeys(keys, value)

Parameters

The fromkeys() method requires two parameters. One is an iterable that contains the keys of the dictionary to be returned.

The second parameter is the value of all the keys, and is an optional argument.

If the second argument is not passed, the default value of the keys is set to None.

Code

Example 1

dictionary = dict.fromkeys(['1', '2,', '3'], '420')
print(dictionary)

Example 2

#Dictionary created without optional values argument
dictionary = dict.fromkeys(['1', '2', '3'])
print(dictionary)

Free Resources