Initializing dictionary with Empty Lists in Python
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
# 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))
OutputNew 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
# 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
# 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)))
OutputNew 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
# 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)))
OutputNew 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
# 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.
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': []}
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:
Similar Reads
Initialize an Empty Dictionary in Python
To initialize an empty dictionary in Python, we need to create a data structure that allows us to store key-value pairs. Different ways to create an Empty Dictionary are:Use of { } symbolUse of dict() built-in functionInitialize a dictionaryUse of { } symbolWe can create an empty dictionary object b
3 min read
How to Initialize a List in Python
Python List is an ordered collections on items, where we can insert, modify and delete the values. Let's first see how to initialize the list in Python with help of different examples. Initialize list using square brackets []Using [] we can initialize an empty list or list with some items. Python# I
2 min read
Initialize empty string in Python
An empty string in Python is simply a string that has no characters in it. It is often used when we need to represent "nothing" or initialize a string variable.In this article, we will explore how to create an empty string in Python using different methods.Using Two Quotation MarksThe simplest way t
1 min read
Python - Remove empty value types in dictionaries list
Sometimes, while working with Python dictionaries, we require to remove all the values that are virtually Null, i.e does not hold any meaningful value and are to be removed before processing data, this can be an empty string, empty list, dictionary, or even 0. This has applications in data preproces
7 min read
Declare an Empty List in Python
Declaring an empty list in Python creates a list with no elements, ready to store data dynamically. We can initialize it using [] or list() and later add elements as needed.Using Square Brackets []We can create an empty list in Python by just placing the sequence inside the square brackets[]. To dec
3 min read
Python | Delete items from dictionary while iterating
A dictionary in Python is an ordered collection of data values. Unlike other Data Types that hold only a single value as an element, a dictionary holds the key: value pairs. Dictionary keys must be unique and must be of an immutable data type such as a: string, integer or tuple. Note: In Python 2 di
3 min read
Python | Convert list of tuple into dictionary
Given a list containing all the element and second list of tuple depicting the relation between indices, the task is to output a dictionary showing the relation of every element from the first list to every other element in the list. These type of problems are often encountered in Coding competition
8 min read
Python - Find dictionary keys present in a Strings List
Sometimes, while working with Python dictionaries, we can have problem in which we need to perform the extraction of dictionary keys from strings list feeded. This problem can have application in many domains including data. Lets discuss certain ways in which this task can be performed. Method #1: U
7 min read
Few mistakes when using Python dictionary
Usually, A dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. Each key-value pair in a Dictionary is separated by a 'colon', whereas each key is separated by a âcommaâ. Python3 1== my_dict = {
3 min read
Iterate over a dictionary in Python
In this article, we will cover How to Iterate Through a Dictionary in Python. To Loop through values in a dictionary you can use built-in methods like values(), items() or even directly iterate over the dictionary to access values with keys.How to Loop Through a Dictionary in PythonThere are multipl
6 min read