How to Loop Through a Dictionary in Python
Python is a high-level programming language that is widely used by data analysts, software developers, and system administrators. One of the most powerful features of Python is its ability to work with data structures like dictionaries, which are often used for storing and manipulating large sets of data. In this article, we will show you how to loop through a dictionary in Python, which is an essential skill for any programmer.
First, let us understand what a dictionary is. A dictionary is a collection of key-value pairs, where each key is associated with a unique value. Dictionaries are unordered and can be modified at any time during the execution of a Python program.
Loop through a Dictionary using the Keys
The simplest way to loop through a dictionary in Python is by iterating over the keys of the dictionary. This can be done using a for loop in combination with the dictionary’s keys() method. Here is an example:
“`
# create a dictionary
my_dict = {‘name’: ‘John’, ‘age’: 25, ‘gender’: ‘male’}
# loop through the keys of the dictionary
for key in my_dict.keys():
print(key)
“`
Output:
“`
name
age
gender
“`
In the above code, we first create a dictionary named `my_dict` with three key-value pairs. Then we use a for loop to iterate over the keys of `my_dict` using the `keys()` method. Inside the for loop, we print each key using the `print()` function.
Loop through a Dictionary using the Values
We can also loop through the values of a dictionary by using the `values()` method. This method returns a list of all the values in the dictionary. Here is an example of how to do it:
“`
# create a dictionary
my_dict = {‘name’: ‘John’, ‘age’: 25, ‘gender’: ‘male’}
# loop through the values of the dictionary
for value in my_dict.values():
print(value)
“`
Output:
“`
John
25
male
“`
In the above code, we first create a dictionary named `my_dict`. Then we use a for loop to iterate over the values of `my_dict` using the `values()` method. Inside the for loop, we print each value using the `print()` function.
Loop through a Dictionary using both Keys and Values
Sometimes we may need to loop through both the keys and values of a dictionary. This can be done using the `items()` method, which returns a list of key-value pairs as tuples. Here is an example:
“`
# create a dictionary
my_dict = {‘name’: ‘John’, ‘age’: 25, ‘gender’: ‘male’}
# loop through the items of the dictionary
for key, value in my_dict.items():
print(key, value)
“`
Output:
“`
name John
age 25
gender male
“`
In the above code, we first create a dictionary named `my_dict`. Then we use a for loop to iterate over the items of `my_dict` using the `items()` method. Inside the for loop, we use tuple unpacking to assign each key-value pair to separate variables, which we then print using the `print()` function.