Open In App

How to create list of dictionary in Python

Last Updated : 25 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In this article, we are going to discuss ways in which we can create a list of dictionaries in Python.  Let’s start with a basic method to create a list of dictionaries using Python.

# Creating a list of dictionaries
a = [{"name": "Alice", "age": 25}, {"name": "Bob", "age": 30}]

print(a)
print(type(a))

Output
[{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]
<class 'list'>

We created a list a containing two dictionaries. Each dictionary has keys like “name” and “age” and their corresponding values. Let’s explore other methods to create a list of dictionaries.

Creating a List of Dictionaries Using a Loop

Creating a list of dictionaries using a for loop is efficient approach. We can dynamically generate dictionaries.

a = []

# Using a loop to create a list of dictionaries
for i in range(3):
    a.append({"name": f"Person {i+1}", "age": 20 + i})
print(a)

Output
[{'name': 'Person 1', 'age': 20}, {'name': 'Person 2', 'age': 21}, {'name': 'Person 3', 'age': 22}]

Creating a List of Dictionaries using List Comprehension

List comprehension is a compact way to create lists. We can use it to create a list of dictionaries in just one line.

a = [{"name": f"Person {i+1}", "age": 20 + i} for i in range(3)]

# Using list comprehension to create a list of dictionaries
print(a)

Output
[{'name': 'Person 1', 'age': 20}, {'name': 'Person 2', 'age': 21}, {'name': 'Person 3', 'age': 22}]

Creating a List of Dictionaries from Lists

If we already have a list of data, and we want to turn it into a list of dictionaries. We can use a loop or list comprehension to do this.

# Creating a list of dictionaries from another list
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 22]

a = [{"name": names[i], "age": ages[i]} for i in range(len(names))]
print(a)

Output
[{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'age': 22}]

Accessing Dictionary Elements from a List of Dictionaries

We can access the elements in a list of dictionaries by using indexing for the dictionary and the keys for specific values inside the dictionary.

lod = [
    {'name': 'Alice', 'age': 25, 'city': 'New York'},
    {'name': 'Bob', 'age': 30, 'city': 'Los Angeles'},
    {'name': 'Charlie', 'age': 35, 'city': 'Chicago'}
]

# Access the second dictionary in the list
d1 = lod[1]
print(d1)  
print(lod[0]['name'])  

Output
{'name': 'Bob', 'age': 30, 'city': 'Los Angeles'}
Alice


Next Article

Similar Reads

three90RightbarBannerImg