Adding Items to a Dictionary in a Loop in Python
Last Updated :
19 Jan, 2024
In Python, we can dynamically add items to a dictionary within a loop using the dictionary’s key-value assignment. In this article, we will learn how to add Items to a Dictionary in a Loop using Python Programming. Below is an example to understand the problem statement.
Example:
Input: keys = ['Name', 'Website', 'Topic', 'Founded']
values = ['GeeksforGeeks', 'https://www.geeksforgeeks.org/', 'Programming', 2009]
Output:
{'Name': 'GeeksforGeeks', 'Website': 'https://www.geeksforgeeks.org/', 'Topic': 'Programming', 'Founded': 2009}
Adding Items to a Dictionary in a Loop in Python
There are different methods to add Items to a Dictionary in a Loop in Python. Below we are explaining all the possible approaches with practical implementation.
- Using for loop and update Method
- Using zip Method
- Using enumerate Method
Add Items to a Python Dictionary Using For Loop and update Method
In this approach, we use the loop to iterate over keys and values and update the dictionary using the update() method. This approach creates the Dictionary and stores it in the output variable and we are printing this variable.
Python3
keys = [ 'Name' , 'Website' , 'Topic' , 'Founded' ]
output = {}
for i in range ( len (keys)):
output.update({keys[i]: values[i]})
print (output)
|
Output
{'Name': 'GeeksforGeeks', 'Website': 'https://www.geeksforgeeks.org/', 'Topic': 'Programming', 'Founded': 2009}
Adding Items to a Dictionary in a Loop Using zip Method
In this approach, we are using the zip() method in the for loop, which pairs corresponding keys and values to the output dictionary. This approach properly creates the dictionary and adds it to the output variable.
Python3
keys = [ 'Name' , 'Website' , 'Topic' , 'Founded' ]
output = {}
for key, value in zip (keys, values):
output[key] = value
print (output)
|
Output
{'Name': 'GeeksforGeeks', 'Website': 'https://www.geeksforgeeks.org/', 'Topic': 'Programming', 'Founded': 2009}
Python Add to Dictionary in a loop Using enumerate Method
In this approach, we are using the enumerate() method in the for loop to iterate over the keys, using the index to access the corresponding values and adding them to the output dictionary variable.
Python3
keys = [ 'Name' , 'Website' , 'Topic' , 'Founded' ]
output = {}
for i, key in enumerate (keys):
output[key] = values[i]
print (output)
|
Output
{'Name': 'GeeksforGeeks', 'Website': 'https://www.geeksforgeeks.org/', 'Topic': 'Programming', 'Founded': 2009}
Share your thoughts in the comments
Please Login to comment...