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.
Frequently Asked:
- Adding Duplicate Key to a Python Dictionary
- Python dict pop()
- Python : How to copy a dictionary | Shallow Copy vs Deep Copy
- Add an Array to a Python Dictionary
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.