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


Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay