This tutorial will discuss about unique ways to initialize a dictionary with keys in Python.
Table Of Contents
Using Dictionary comprehension
Suppose we have a list of keys and we want to create a dictionary from these keys.
But as the dictionary store the values in the key value pairs so, we want the value of each pair to be a default value 11.
We can do that using a dictionary comprehension. We will iterate over all the keys in the list using for loop. During iteration, for each key, we will create a key value pair and assign the default value 11 to that pair, and add it into the dictionary using the dictionary comprehension.
Let’s see the complete example,
listOfKeys = ['Ritika', 'Atharv', 'Smriti', 'Mathew', 'John'] # Default Value value = 11 # Initialize a Dictionary using dictionary comprehension dictObj = { key: value for key in listOfKeys } print(dictObj)
Output
Frequently Asked:
- Python: Iterate over a dictionary sorted by key
- Python: Iterate / Loop over Dictionary (All key-value pairs)
- How to Initialize a Dictionary of Dictionaries in Python?
- Python: Print all key-value pairs of a dictionary
{'Ritika': 11, 'Atharv': 11, 'Smriti': 11, 'Mathew': 11, 'John': 11}
Using the fromkeys() method
Dictionary provides a method fromkeys(). It accepts two arguments, first is the list of keys and second is the value that every key should have in a new dictionary, and returns a new dictionary initialized withese arguments.
So, if you want to initialise a dictionary with the list, you can pass the list as the first argument and the default value as the second argument. It will return a dictionary object where each key will be picked from the list and every key will have the default value, which we provided as a second argument.
Like, the below example we are going to create a dictionary from the keys in the list and each key will have default value 11.
Let’s see the complete example,
listOfKeys = ['Ritika', 'Atharv', 'Smriti', 'Mathew', 'John'] # Default Value value = 11 dictObj = dict.fromkeys(listOfKeys, value) print(dictObj)
Output
{'Ritika': 11, 'Atharv': 11, 'Smriti': 11, 'Mathew': 11, 'John': 11}
Summary
We learned about two ways to Initialize a Dictionary With Keys in Python.