Python Dictionary fromkeys()

Python dictionary fromkeys() method

Python dictionary fromkeys() class method returns a new dictionary created with the given list of keys and default value for the items.

In this tutorial, you will learn about dictionary fromkeys() class method in Python, and its usage, with the help of example programs.

Syntax of dict fromkeys()

The syntax of dictionary fromkeys() method is

dict.fromkeys(iterable, value)

Parameters

ParameterDescription
iterableRequired
The items of this iterable will be used as keys for creating the dictionary.
valueOptional
This is the default value for all the items in the dictionary.
If not specified, then None is considered as the default value.
Python dictionary fromkeys() class method parameters

Return value

The dictionary fromkeys() method returns a dictionary of type dict.

fromkeys() is a class method, not instance method. Therefore, you can call fromkeys() method only using dict class as dict.fromkeys(). You cannot call this method on a dictionary object.

Examples for fromkeys() method

1. Creating a dictionary with a list of strings as keys and a default value, using fromkeys() method in Python

In this example, we are given a list of strings in keys_list with some initial string values, and an integer value of 20 in variable default_value. We have to create a dictionary with the items in keys_list as keys of the dictionary, the default_value as value for each key.

Call fromkeys() class method on the dict class, and pass the keys_list and default_value as arguments. The method returns a dictionary, and we shall print this dictionary to output.

Python Program

keys_list = ['foo', 'bar', 'moo']
default_value = 20

my_dict = dict.fromkeys(keys_list, default_value)
print(my_dict)
Run Code Copy

Output

{'foo': 20, 'bar': 20, 'moo': 20}

2. Creating a dictionary with a list of keys, no default value specified, using fromkeys() method

In this example, we create a dictionary from the keys given in a list, just as we have done in the previous example. The catch is that we do not given any default value (second argument to fromkeys() method).

Python Program

keys_list = ['foo', 'bar', 'moo']

my_dict = dict.fromkeys(keys_list)
print(my_dict)
Run Code Copy

Since no default value is specified for the items in the dictionary, the value None shall be considered.

Output

{'foo': None, 'bar': None, 'moo': None}

Summary

In this tutorial of Python Dictionary Methods, we learned how to use Dictionary fromkeys() class method to create a dictionary from given iterable of keys. We have used list object as iterable for keys. You may also use a tuple, or keys from another dictionary, etc., as iterable for the keys.

Related Tutorials

Code copied to clipboard successfully 👍