How to create empty List of Dictionaries in Python : 3 Methods

Dictionary is a data structure in python that stores value key-value pairs. It is an ordered, mutable and unique collection of pairs. But how to initialize the empty list of dictionaries.? In this entire post, you will learn how to create an empty list of dictionaries in python using various methods.

Create an empty list of dictionaries in python

Let’s know all the methods to create a list of dictionaries in python.

Method 1: Using the multiplication operator

Here you will first define the empty dictionary. Then wrap the dictionary in a list and multiply with the number of dictionaries you want inside the list.

empty_dict = {}
list_of_dict = [{}] *5
print(list_of_dict)

Output

[{}, {}, {}, {}, {}]

You can check the type of the list of dictionaries using the type() function.

type(list_of_dict)

Output

list

Method 2: Create an empty list of dictionaries using list comprehension

List comprehension allows writing the loop in a single statement. You will use it for creating an empty list of dictionaries. Let’s say you want five dictionaries inside the list then iterate 5 times and with each iteration create a dictionary inside the list.

no_of_dict = 5
list_of_dict = [{} for i in range(no_of_dict)]
print(list_of_dict)

Output

[{}, {}, {}, {}, {}]

In the same way, you can create 6,7,8 e.t.c unlimited number of dictionaries inside the list by looping a number of times.

Method 3: Using for loop with dict() function

You can also use for loop with the dict() function to define the empty dictionaries inside the list. Here you will create an empty list and append the empty dictionary in each iteration in it.

empty_list = []
for i in range(5):
empty_list.append({})
print(empty_list)

Output

[{}, {}, {}, {}, {}]

These are the method to initialize or create an empty list of dictionaries in python. You can use any method according to your convenience.

Code The Best
Hi, I am CodeTheBest. Here you will learn the best coding tutorials on the latest technologies like a flutter, react js, python, Julia, and many more in a single place.