Adding Items to a Dictionary in a Loop in Python
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 = ['w3wiki', 'https://www.w3wiki.net/', 'Programming', 2009]
Output:
{'Name': 'w3wiki', 'Website': 'https://www.w3wiki.net/', '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
# input data for dict keys = [ 'Name' , 'Website' , 'Topic' , 'Founded' ] # creating an empty dictionary output = {} # adding items to the dictionary using a loop for i in range ( len (keys)): output.update({keys[i]: values[i]}) # print output print (output) |
{'Name': 'w3wiki', 'Website': 'https://www.w3wiki.net/', '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
# input data for dict keys = [ 'Name' , 'Website' , 'Topic' , 'Founded' ] # creating an empty dictionary output = {} # adding items to the dictionary using a loop for key, value in zip (keys, values): output[key] = value # print output print (output) |
{'Name': 'w3wiki', 'Website': 'https://www.w3wiki.net/', '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
# input data for dict keys = [ 'Name' , 'Website' , 'Topic' , 'Founded' ] # creating an empty dictionary output = {} # adding items to the dictionary using a loop for i, key in enumerate (keys): output[key] = values[i] # print output print (output) |
{'Name': 'w3wiki', 'Website': 'https://www.w3wiki.net/', 'Topic': 'Programming', 'Founded': 2009}
Contact Us