How to Create List of Dictionary in Python Using For Loop
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
- 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) |
[{'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) |
[{'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
# Define a list of fruits fruits = [ "Apple" , "Orange" , "Banana" ] # Define a list of corresponding prices for each fruit prices = [ 5 , 3 , 2 ] # Initialize an empty list to store dictionaries containing fruit information fruit_info = [] # Iterate over each fruit in the list of fruits for i, fruit in enumerate (fruits): # Append a dictionary containing the name of the fruit and its corresponding price fruit_info.append({ "name" : fruit, "price" : prices[i]}) # Print the list of dictionaries containing fruit information print (fruit_info) |
[{'name': 'Apple', 'price': 5}, {'name': 'Orange', 'price': 3}, {'name': 'Banana', 'price': 2}]
Contact Us