How to Store Values in Dictionary in Python Using For Loop
Last Updated :
24 Jan, 2024
In this article, we will explore the process of storing values in a dictionary in Python using a for loop. As we know, combining dictionaries with for loops is a potent technique in Python, allowing iteration over keys, values, or both. This discussion delves into the fundamentals of Python dictionaries and provides a demonstration of how to effectively store values within a dictionary using a for loop.
Store Values in Dictionary in Python Using For Loop
Here, are methods for storing values in a Python dictionary using a for loop.
- Using For Loop
- Using Zip Function
- Using Enumerate Function
Store Values in Dictionary in Python Using For Loop
In this example, below Python code below establishes an empty dictionary named my_dict
and provides sample data with keys (e.g., ‘name’, ‘age’, ‘city’) and corresponding values (e.g., ‘John’, 25, ‘New York’). Through a for loop, it populates the dictionary by assigning values to their respective keys.
Python3
my_dict = {}
keys = [ 'name' , 'age' , 'city' ]
values = [ 'John' , 25 , 'New York' ]
for i in range ( len (keys)):
my_dict[keys[i]] = values[i]
print (my_dict)
|
Output :
{'name': 'John', 'age': 25, 'city': 'New York'}
Store Values in Dictionary in Python Using zip Function
In this Python example, the zip
function is utilized to pair up the elements from the keys
and values
lists, and a dictionary named my_dict
is created using a concise dictionary comprehension. This approach simplifies the process of combining keys and values, resulting in a dictionary with the specified key-value pairs.
Python3
keys = [ 'name' , 'age' , 'city' ]
values = [ 'John' , 25 , 'New York' ]
my_dict = {key: value for key,
value in zip (keys, values)}
print (my_dict)
|
Output :
{'name': 'John', 'age': 25, 'city': 'New York'}
Store Values in Dictionary in Python Using enumerate Function
In this example, below Python code, two lists, `keys` and `values`, are provided. An empty dictionary named `my_dict` is initialized. The for loop, utilizing `enumerate()`, iterates through the keys, pairs them with corresponding values using the index `i`, and populates the dictionary.
Python3
keys = [ 'name' , 'age' , 'city' ]
values = [ 'John' , 25 , 'New York' ]
my_dict = {}
for i, key in enumerate (keys):
my_dict[key] = values[i]
print (my_dict)
|
Output :
{'name': 'John', 'age': 25, 'city': 'New York'}
Share your thoughts in the comments
Please Login to comment...