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

In Python, you can iterate over a dictionary using various techniques. Here's a detailed explanation of a few commonly used methods: Iterating over keys: By default, when you iterate over a dictionary using a loop, it iterates over the keys of the dictionary.

1
2
3
4
5

my_dict = {'a': 1, 'b': 2, 'c': 3}

for key in my_dict:
    print(key)

In this example, the loop iterates over the keys of themy_dict dictionary, and each key is printed. Iterating over values: To iterate over the values of a dictionary, you can use thevalues() method.

1
2
3
4
5

my_dict = {'a': 1, 'b': 2, 'c': 3}

for value in my_dict.values():
    print(value)

In this example, the loop uses thevalues() method to iterate over the values of themy_dict dictionary, and each value is printed. Iterating over key-value pairs: To iterate over both the keys and values of a dictionary simultaneously, you can use theitems() method.

1
2
3
4
5

my_dict = {'a': 1, 'b': 2, 'c': 3}

for key, value in my_dict.items():
    print(key, value)

In this example, the loop uses theitems() method to iterate over the key-value pairs of themy_dict dictionary. The loop assigns each key to the variablekey and each value to the variablevalue, and they are printed together. Using list comprehension: You can also use list comprehension to create a new list based on the dictionary's keys, values, or items.

1
2
3
4
5
6
7
8
9
10

my_dict = {'a': 1, 'b': 2, 'c': 3}

keys = [key for key in my_dict]
values = [value for value in my_dict.values()]
items = [(key, value) for key, value in my_dict.items()]

print(keys)
print(values)
print(items)

In this example, list comprehensions are used to create new lists based on the keys, values, or items of themy_dict dictionary. The resulting lists are then printed. These are a few commonly used methods to iterate over a dictionary in Python. Choose the method that best suits your needs based on whether you want to iterate over the keys, values, or key-value pairs of the dictionary.