Python – Initialize a Dictionary with default value

This tutorial will discuss about unique ways to initialize a dictionary with default value in Python.

Table Of Contents

Suppose you have a list of strings, and you want to initialize a dictionary with this List items as keys, and with a default value for each key.

Where, we will iterate over the sequence of keys and for each key we will assign a defauly value 19, in the dictionary comprehension. It will return a dictionary containing pairs, where keys will be from the list but each pair will have a default value 19.

Using dictionary Comprehension

Let’s see the complete example,

listOfKeys = ['Sanjay', 'Ritika', 'Smriti', 'Justin', 'John']

defaultValue = 19

# Initialize a Dictionary with default values
dictObj = {key: defaultValue for key in listOfKeys}

print(dictObj)

Output

{'Sanjay': 19, 'Ritika': 19, 'Smriti': 19, 'Justin': 19, 'John': 19}

Using fromkeys() method

To initialise a dictionary with list of keys and a default value, we can use the fromkeys() method from the dictionary. We will pass the list of keys as first argument and the default value as the second argument in the fromkeys() method.

It will initialise, and return a dictionary object, where the items from the list listOfKeys will be the keys in the key-value pairs, and each key will have a default value, which we provided as second argument in the fromkeys() method.

In the belowe example, we will initialize a Dictionary with a list of strings, and a default value 19.

Let’s see the complete example,

listOfKeys = ['Sanjay', 'Ritika', 'Smriti', 'Justin', 'John']

defaultValue = 19

# Initialize a Dictionary with default values
dictObj = dict.fromkeys(listOfKeys, defaultValue)

print(dictObj)

Output

{'Sanjay': 19, 'Ritika': 19, 'Smriti': 19, 'Justin': 19, 'John': 19}

Summary

We learned about two ways to initialize a dictionary with default values in python.

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