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
new_dict = {new_list: [] for new_list in range ( 4 )}
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
alphabets = { 'a' , 'b' , 'c' }
number = 10
dictionary = dict .fromkeys(alphabets, number)
print (dictionary)
|
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
from collections import defaultdict
new_dict = defaultdict( list )
new_dict[ 0 ].append( 'GeeksforGeeks' )
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
new_dict = {}
[new_dict.setdefault(x, []) for x in range ( 4 )]
new_dict[ 0 ].append( 'GeeksforGeeks' )
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
keys = range ( 4 )
new_dict = dict ( zip (keys, ([] for _ in keys)))
print (new_dict)
new_dict[ 0 ].append( 'GeeksforGeeks' )
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
keys = [ 'a' , 'b' , 'c' ]
values = list (itertools.repeat([], len (keys)))
key_value_pairs = zip (keys, values)
my_dict = dict (key_value_pairs)
print (my_dict)
|
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