Open In App

Create Dynamic Dictionary using for Loop-Python

Last Updated : 01 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The task of creating a dynamic dictionary using a for loop in Python involves iterating through a list of keys and assigning corresponding values dynamically. This method allows for flexibility in generating dictionaries where key-value pairs are added based on specific conditions or inputs during iteration.

For example, given two lists ["name", "age", "city"] and ["Rahul", 25, "New York"], the goal is to construct a dictionary like {'name': 'Rahul', 'age': 25, 'city': 'New York'} by iterating over both lists simultaneously. This approach ensures that each key from the first list is mapped to its corresponding value from the second list efficiently.

Using zip()

zip() pairs elements from multiple iterables e.g., two lists element by element. When combined with a for loop, it enables us to iterate over two lists simultaneously and creating key-value pairs to dynamically build a dictionary. This method is efficient, eliminating the need for indexing and making it a more Pythonic solution compared to a simple for loop that relies on indices.

Python
a = ['name', 'age', 'city']
b = ['Rahul', 25, 'New York']

d = {} # initialize empty dictionary

for key, val in zip(a, b):
    d[key] = val

print(d)

Output
{'name': 'Rahul', 'age': 25, 'city': 'New York'}

Explanation: zip() pairs corresponding elements from lists a and b, creating key-value pairs. The for loop then iterates through these pairs, adding each to the dictionary d using d[key] = val, dynamically building the dictionary.

Using dictionary comprehension

Dictionary comprehension allows us to create dictionaries in a compact, readable format. It is a one-liner approach that combines iterating over lists and dynamically assigning keys and values. When combined with zip() it offers a efficient way to generate dynamic dictionaries.

Python
a = ['name', 'age', 'city']
b = ['Rahul', 25, 'New York']

d = {key: val for key, val in zip(a, b)}
print(d)

Output
{'name': 'Rahul', 'age': 25, 'city': 'New York'}

Explanation: zip() pairs elements from lists a and b, and the dictionary comprehension {key: val for key, val in zip(a, b)} creates the dictionary d by iterating over these pairs, dynamically assigning keys and values.

Using items

items() provides a view of all key-value pairs in an existing dictionary. We can use it to dynamically generate a new dictionary by iterating over these pairs. This approach is useful when merging multiple dictionaries or when we need to transform an existing dictionary’s key-value pairs into a new one.

Python
a = {'name': 'Rahul', 'age': 25}
b = {'city': 'New York', 'country': 'USA'}

d = {} # initialize empty dictionary
for key, val in a.items():
    d[key] = val
for key, val in b.items():
    d[key] = val

print(d)

Output
{'name': 'Rahul', 'age': 25, 'city': 'New York', 'country': 'USA'}

Explanation: This code uses two for loops to iterate over the key-value pairs in dictionaries a and b using items(), adding each pair to d. This merges the contents of both dictionaries into d.

Using update()

update() allows us to add key-value pairs from one dictionary to another. When using it in a for loop, we can dynamically merge key-value pairs from multiple sources into a single dictionary. This approach is efficient when we need to merge dictionaries or dynamically update an existing dictionary with new data.

Python
a = {'name': 'Rahul'}
b = {'age': 25}
c = {'city': 'New York'}

d = {} # initialize empty dictionary
for i in [a, b, c]:
    d.update(i)

print(d)

Output
{'name': 'Rahul', 'age': 25, 'city': 'New York'}

Explanation: a for loop iterate over the dictionaries a, b, and c. In each iteration, update() method is used to add the key-value pairs from the current dictionary i to d. This effectively merges all the dictionaries into d .


Next Article
Practice Tags :

Similar Reads