![]() |
VOOZH | about |
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.
[{'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.
Table of Content
Creating a list of dictionaries using a for loop is efficient approach. We can dynamically generate dictionaries.
[{'name': 'Person 1', 'age': 20}, {'name': 'Person 2', 'age': 21}, {'name': 'Person 3', 'age': 22}]
List comprehension is a compact way to create lists. We can use it to create a list of dictionaries in just one line.
[{'name': 'Person 1', 'age': 20}, {'name': 'Person 2', 'age': 21}, {'name': 'Person 3', 'age': 22}]
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.
[{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'age': 22}]
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.
{'name': 'Bob', 'age': 30, 'city': 'Los Angeles'}
Alice