Open In App

Initializing dictionary with Empty Lists in Python

In Python, it’s common to encounter scenarios where you need to store lists in a dictionary. Often, this involves checking if a key exists and then creating a list for that key. However, a more efficient approach is to initialize the dictionary keys with empty lists from the start. Let’s explore some methods to accomplish this.

How to Initialize a Dictionary with an Empty List

It is a good practice to initialize a dictionary with empty lists in Python. This helps in working with dynamic data structures. This also helps in appending items to a list associated with a key.



Initializing an empty list while creating a dictionary also eases the process of later creating a list while checking for key availability.

We will learn various methods to initialize an empty list dictionary.



Initialize a Dictionary of Empty Lists using Dictionary Comprehension

Dictionary comprehension is the most sought method to do this initialization. In this method, we create the no. of keys we require and then initialize the empty list as we keep on creating the keys, to facilitate the append operation afterward without an error. 




# Python3 code to demonstrate
# to initialize dictionary with list
# using dictionary comprehension
 
# using dictionary comprehension to construct
new_dict = {new_list: [] for new_list in range(4)}
     
# printing result
print ("New dictionary with empty lists as keys : " + str(new_dict))

Output
New dictionary with empty lists as keys : {0: [], 1: [], 2: [], 3: []}


Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n), to store the keys and values in dictionary.

Create Empty List of Dictionaries using fromkeys()

Using fromkeys() you can create a dictionary from the given sequence of keys and values.




# keys for the dictionary
alphabets = {'a', 'b', 'c'}
 
# value for the dictionary
number = 10
 
# creates a dictionary with keys and values
dictionary = dict.fromkeys(alphabets, number)
 
print(dictionary)
 
# Output: {'a': 1, 'c': 1, 'b': 1}

Output
{'b': 10, 'a': 10, 'c': 10}


Create Empty List of Dictionaries using defaultdict

This is the most pythonic way and error-free way to use dictionary key without needing to initialize its value. It has to be told the type of default container of all its keys and then dictionary automatically evaluates the operations and structures accordingly. 
 




# Python3 code to demonstrate
# to initialize dictionary with list
# using defaultdict
from collections import defaultdict
 
# initializing dict with lists
new_dict = defaultdict(list)
 
# performing append
# shows no error
new_dict[0].append('GeeksforGeeks')
     
# printing result
print ("New dictionary created : " + str(dict(new_dict)))

Output
New dictionary created : {0: ['GeeksforGeeks']}


Python Initialize Dictionary using setdefault

This can be used to perform by specifying key-value pairs within a comprehension. This method obviates the need to import a module as is required in the above method.




# Python3 code to demonstrate
# to initialize dictionary with list
# using setdefault
 
# initializing dict with lists
new_dict = {}
[new_dict.setdefault(x, []) for x in range(4)]
 
# performing append
# shows no error
new_dict[0].append('GeeksforGeeks')
     
# printing result
print ("New dictionary created : " + str(dict(new_dict)))

Output
New dictionary created : {0: ['GeeksforGeeks'], 1: [], 2: [], 3: []}


Initialize Dictionary with Empty List using built-ins: dict and zip

The built-in functions dict, and zip in conjunction with list comprehension can achieve the desired result. 




# Python3 code to demonstrate
# use of dict() and zip() built-ins to demonstrate
# initializing dictionary with list
 
keys = range(4)
new_dict = dict(zip(keys, ([] for _ in keys)))
 
print(new_dict)  # performing append
# shows no error
new_dict[0].append('GeeksforGeeks')
 
# printing result
print("New dictionary created : " + str(dict(new_dict)))

Output
{0: [], 1: [], 2: [], 3: []}
New dictionary created : {0: ['GeeksforGeeks'], 1: [], 2: [], 3: []}


Initialize Dictionary with Empty List using Itertools

Here is an example of using the itertools module to initialize a dictionary with empty lists using itertools.




import itertools
 
# Initialize a list of keys
keys = ['a', 'b', 'c']
 
# Use itertools.repeat to create a list of empty lists
values = list(itertools.repeat([], len(keys)))
 
# Use the zip function to create a list of tuples containing the keys and values
key_value_pairs = zip(keys, values)
 
# Use the dict function to create a dictionary from the key-value pairs
my_dict = dict(key_value_pairs)
 
print(my_dict)  # {'a': [], 'b': [], 'c': []}

Output
{'a': [], 'b': [], 'c': []}


Explanation:

We have covered various methods to initialize a dictionary with empty list. Using lists inside a dictionary is very useful, and you should try to make the dictionary with empty list so that you can use it in future without worrying to add new list.

Also Read:


Article Tags :