How do I iterate over a dictionary in Python?
Rashid D
rashid d profile pic

In Python, there are multiple ways to iterate over a dictionary. Here's a detailed explanation of some commonly used approaches: 1. Iterating over keys using afor loop:

1
2
3
4
5
6
7
8
9

my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}

# Iterate over keys
for key in my_dict:
    # Access the value using the key
    value = my_dict[key]
    # Process the key-value pair
    print(key, value)

In this approach, thefor loop iterates over the keys of the dictionary. Within the loop, you can access the corresponding value using the key. 2. Iterating over keys and values using theitems() method:

1
2
3
4
5
6
7

my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}

# Iterate over keys and values
for key, value in my_dict.items():
    # Process the key-value pair
    print(key, value)

Theitems() method returns a view object that contains key-value pairs as tuples. By using thefor loop with tuple unpacking, you can iterate over both keys and values simultaneously. 3. Iterating over keys using thekeys() method:

1
2
3
4
5
6
7
8
9

my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}

# Iterate over keys
for key in my_dict.keys():
    # Access the value using the key
    value = my_dict[key]
    # Process the key-value pair
    print(key, value)

Thekeys() method returns a view object that contains the keys of the dictionary. You can iterate over this view object to access the keys and obtain their corresponding values. 4. Iterating over values using thevalues() method:

1
2
3
4
5
6
7

my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}

# Iterate over values
for value in my_dict.values():
    # Process the value
    print(value)

Thevalues() method returns a view object that contains the values of the dictionary. You can directly iterate over this view object to access the values. These are some of the commonly used methods to iterate over a dictionary in Python. Choose the approach that best suits your needs and the specific information you need to process from the dictionary.