How to Initialize a Dictionary with 0 in Python?

This tutorial will discuss about a unique way to initialise a dictionary with 0 in Python?.

Suppose we have a list of keys. Like this,

listOfKeys = ['Ritika', 'Atharv', 'Smriti', 'Mathew', 'John']

We want to initialise dictionary from these keys but each key should have a default value zero associated with it. Like this,

{'Ritika': 0,
 'Atharv': 0,
 'Smriti': 0,
 'Mathew': 0,
 'John': 0}

We can do this using the fromkeys() method of the dictionary.

We will pass the list of keys as first argument and zero as the second argument in the the fromkeys() method. It will returna new a dictionary initialized with these arguments. In this new dictionary, every key will have value zero associated with it. Code is like this,

# Create a dictionary with 0 as default value
dictObj = dict.fromkeys(listOfKeys, 0)

This dictionary will have zero as the default value.

Let’s see the complete example,

listOfKeys = ['Ritika', 'Atharv', 'Smriti', 'Mathew', 'John']

# Create a dictionary with 0 as default value
dictObj = dict.fromkeys(listOfKeys, 0)

print(dictObj)

Output

{'Ritika': 0, 'Atharv': 0, 'Smriti': 0, 'Mathew': 0, 'John': 0}

Summary

We learned how to create a Dictionary with 0 as default values.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top