How to Create List of Dictionary in Python Using For Loop
The task of creating a list of dictionaries in Python using a for loop involves iterating over a sequence of values and constructing a dictionary in each iteration. By using a for loop, we can assign values to keys dynamically and append the dictionaries to a list. For example, with a list of keys a = ['key', 'value'] and iterating over a range of numbers, the task would be to create dictionaries . The result will be [{'key': 0, 'value': 0}, {'key': 1, 'value': 2}, {'key': 2, 'value': 4}] .
Using list comprehension
List comprehension is a efficient way to create lists in Python. It allows us to generate a list of dictionaries in a single line by combining dict() with zip(), making the code clean and readable.
a = ['key', 'value'] # List of keys
b = [dict(zip(a, [i, i * 2])) for i in range(3)]
print(b)
Output
[{'key': 0, 'value': 0}, {'key': 1, 'value': 2}, {'key': 2, 'value': 4}]
Explanation: list comprehension with zip() and dict() to create a list of dictionaries, mapping 'key' to i and 'value' to i * 2 for i in the range 0 to 2.
Using dictionary comprehension
Dictionary comprehension helps create key-value pairs dynamically within dictionaries. When combined with list comprehension, it’s useful for building more complex data structures with clear, compact syntax.
a = ['key', 'value'] # List of keys
b = [{k: (i if k == 'key' else i * 2) for k in a} for i in range(3)]
print(b)
Output
[{'key': 0, 'value': 0}, {'key': 1, 'value': 2}, {'key': 2, 'value': 4}]
Explanation: dictionary comprehension create dictionaries, where 'key' is mapped to i and 'value' to i * 2 for each i in the range 0 to 2.
Using append
append() is used in a for loop to add dictionaries to a list as the loop iterates. This method is simple and beginner-friendly, allowing us to construct dictionaries dynamically and store them in the list. It offers clear logic, making it easy to modify and debug, especially when working with complex conditions.
a = ['key', 'value'] # List of keys
b = [] # Initializing an empty list
for i in range(3):
b.append(dict(zip(a, [i, i * 2])))
print(b)
Output
[{'key': 0, 'value': 0}, {'key': 1, 'value': 2}, {'key': 2, 'value': 4}]
Explanation: for loop iterate over the range 0 to 2, creating dictionaries where 'key' is mapped to i and 'value' is mapped to i * 2 and appends each dictionary to the list b.