This tutorial will discuss about unique ways to initialize a dictionary with empty list in Python.
Table Of Contents
Using Dictionary Comprehension
Dictionary in Python stores the data as a key value pairs. Now suppose you want to store an empty list as a value for each key in the dictionar.
So, we can do that using two ways, first one is a dictionary comprehension. Where, we will iterate over the sequence of keys and for each key we will assign the value as empty list in the dictionary comprehension. It will return a dictionary containing keys from the list but each value will be the empty list.
Let’s see the complete example,
listOfKeys = ['Ritika', 'Atharv', 'Smriti', 'Mathew', 'John'] # Create a dictionary with empty list as values dictObj = {key: [] for key in listOfKeys} print(dictObj)
Output
{'Ritika': [], 'Atharv': [], 'Smriti': [], 'Mathew': [], 'John': []}
Using fromkeys() method
To initialise a dictionary with keys and an empty list as the default value, we can use the fromkeys() method from the dictionary. We will pass the list of keys as first argument and an empty list as the second argument in the fromkeys() method.
Frequently Asked:
- Solved- TypeError: dict_keys object does not support indexing
- Can a dictionary have duplicate keys in Python?
- Python: Pretty print nested dictionaries – dict of dicts
- Get sum of values of a Dictionary in Python
It will initialise, and return a dictionary object, where the items from the list keys will be the keys in the key-value pairs, and each key will have the empty list as default value.
Let’s see the complete example,
listOfKeys = ['Ritika', 'Atharv', 'Smriti', 'Mathew', 'John'] # Create a dictionary with empty list as values dictObj = dict.fromkeys(listOfKeys, []) print(dictObj)
Output
{'Ritika': [], 'Atharv': [], 'Smriti': [], 'Mathew': [], 'John': []}
Summary
We learned about two different ways to initialise a dictionary with an empty list in Python.