DEV Community

Main
Main

Posted on • Originally published at pynerds.com on

dict.fromkeys() method in Python

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Related articles


Top comments (0)