dict.fromkeys() method in Python

RMAG news

Thefromkeys() method of dicttype is used to create a new dictionary with keys from a given iterable and values pre-filled with a specified default value.

The syntax is as shown below:

dict.setdefault(iterable, value = None)

The items in the created dictionary has the elements from the iterableas keys and the specified valueas the default value. If valueis not given, Nonewill be used.

keys = [1, 2, 3, 4, 5]

d = dict.fromkeys(keys)
print(d)

If the default value is given, the item’s values will be populated with the value instead of None.

keys = [‘one’, ‘two’, ‘three’, ‘four’, ‘five’]

d = dict.fromkeys(keys, 0)
print(d)

In the above example, we specified 0 as the default value to thefromkeys() method.

Note that the iterable argument can be any valid iterable not just lists. In the following example we use a range() for the iterable argument.

d = dict.fromkeys(range(5))
print(d)

Related articles

Dictionary in Python

Python dict() Function

dict.get() method in Python

dict.update() method in Python

items(), keys() and values() methods in Python dictionary

dict.pop() in Python

dict.clear() method in Python

dict.popitem() method in Python

dict.setdefault() method in Python

dict.copy() method in Python

Leave a Reply

Your email address will not be published. Required fields are marked *