Open In App
Related Articles

Python | Initializing dictionary with empty lists

Improve Article
Improve
Save Article
Save
Like Article
Like

In python one usually comes across situations in which one has to use a dictionary for storing the lists. But in those cases, one usually checks for first element and then creates a list corresponding to key when it comes. But it always wanted a method to initialize the dict. keys with list. Let’s discuss certain ways to achieve this particular task.

Method #1: Using Dictionary comprehension: This 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, so as to facilitate the append operation afterward without an error. 

Python3




# 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.

Method #2: Using fromkeys(): This method creates a dictionary from the given sequence of keys and values.

Python3




# 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}

Method #3: Using defaultdict: This is the most pythonic way and error-free way to use any key without initialization of its value, it has to be told the type of default container of all its keys and then evaluates the operations and structures accordingly. 
 

Python3




# 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']}

Method #4: Using setdefault: This can be used to perform this by specifying key-value pairs within a comprehension. This method obviates the need to import a module as is required in Method #3. 
 

Python3




# 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: []}

Method #5: Using built-ins: dict and zip: The built-in functions dict, and zip in conjunction with list comprehension can achieve the desired result. 
 

Python3




# 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: []}

Method #6:  Here is an example of using the itertools module to initialize a dictionary with empty lists:

Python3




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': []}

The above code uses the itertools module to initialize a dictionary with empty lists as values.

The itertools.repeat function is used to create a list of len(keys) number of empty lists. This list of empty lists is then assigned to the values variable.

The zip function is then used to create a list of tuples, where each tuple contains a key from the keys list and a value from the values list. This list of tuples is assigned to the key_value_pairs variable.

Finally, the dict function is used to create a dictionary from the key_value_pairs list, and the resulting dictionary is assigned to the my_dict variable.

The dictionary is then printed to the console, and the output should be {‘a’: [], ‘b’: [], ‘c’: []}.

This approach has a time complexity of O(N) and a space complexity of O(N), where N is the number of keys in the dictionary.


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 27 Apr, 2023
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials