Initializing dictionary with Empty Lists in Python (original) (raw)
Last Updated : 20 Dec, 2023
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
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.
Create Empty List of Dictionaries using **fromkeys()
Using fromkeys() you can create 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}
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
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']}
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
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: []}
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
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: []}
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.
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': []}
**Explanation:
- 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.
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: