How to Create List of Dictionary in Python Using For Loop
Last Updated :
13 Feb, 2024
In Python programming, creating a list of dictionaries is a common task, particularly when dealing with structured data. In this article, we will discuss various approaches to create a list of dictionaries in Python using a for loop.
Create a List of Dictionary in Python Using For Loop
Below are some of the ways by which we can create List of Dictionary in Python Using For Loop:
- Using zip() with For Loop
- Using List Comprehension
- Using enumerate() Function
Create a List of Dictionary Using zip() with For Loop
In this example, a list of dictionaries, `list_of_dicts`, is created using a list comprehension and the `zip` function to combine keys (‘key’ and ‘value’) with corresponding values generated in a for loop ranging from 0 to 2. Each dictionary represents an iteration with ‘key’ as the iteration value and ‘value’ as twice the iteration value.
Python3
keys = [ 'key' , 'value' ]
list_of_dicts = [ dict ( zip (keys, [i, i * 2 ])) for i in range ( 3 )]
print (list_of_dicts)
|
Output
[{'key': 0, 'value': 0}, {'key': 1, 'value': 2}, {'key': 2, 'value': 4}]
Create a List of Dictionary Using List Comprehension
In this example, a list of dictionaries, `list_of_dicts`, is generated using a list comprehension. Each dictionary within the list has keys ‘key’ and ‘value’, where ‘key’ corresponds to the iteration value from 0 to 2, and ‘value’ is twice the iteration value. The resulting list is then printed, showcasing a compact approach for creating dictionaries with specified keys and dynamic values.
Python3
list_of_dicts = [{ 'key' : i, 'value' : i * 2 } for i in range ( 3 )]
print (list_of_dicts)
|
Output
[{'key': 0, 'value': 0}, {'key': 1, 'value': 2}, {'key': 2, 'value': 4}]
Create a List of Dictionary Using enumerate() Function
In this code snippet, a list of fruits (`fruits`) and a corresponding list of prices (`prices`) are defined. An empty list (`fruit_info`) is initialized to store dictionaries containing information about each fruit. Using a for loop and the enumerate() function to track the index (`i`), dictionaries are created for each fruit, incorporating its name and the corresponding price. The final list of dictionaries (`fruit_info`) is then printed, providing information about each fruit along with its respective price.
Python3
fruits = [ "Apple" , "Orange" , "Banana" ]
prices = [ 5 , 3 , 2 ]
fruit_info = []
for i, fruit in enumerate (fruits):
fruit_info.append({ "name" : fruit, "price" : prices[i]})
print (fruit_info)
|
Output
[{'name': 'Apple', 'price': 5}, {'name': 'Orange', 'price': 3}, {'name': 'Banana', 'price': 2}]
Share your thoughts in the comments
Please Login to comment...