Write a Python Program to Iterate Over Dictionaries Using for Loop

Python is a versatile and powerful programming language that has a variety of data structures, including dictionaries.

Dictionaries are used to store data in key-value pairs, where each key corresponds to a value.

In this tutorial, we will discuss how to iterate over dictionaries using a for loop in Python.


Iterating over a Dictionary in Python

Iterating over a dictionary in Python is quite simple.

We can use the for loop to iterate over the keys or values of a dictionary.

Here’s an example:

my_dict = {"apple": 1, "banana": 2, "cherry": 3}

# iterate over the keys of the dictionary
for key in my_dict:
    print(key)

# iterate over the values of the dictionary
for value in my_dict.values():
    print(value)

# iterate over both keys and values of the dictionary
for key, value in my_dict.items():
    print(key, value)

Output:

apple
banana
cherry
1
2
3
apple 1
banana 2
cherry 3

In the first loop, we are iterating over the keys of the dictionary.

In each iteration, the key variable takes on the value of the next key in the dictionary.

We can then use this key to access the corresponding value of the dictionary.

In the second loop, we are iterating over the values of the dictionary using the values() method.

This method returns a list of all the values in the dictionary.

In each iteration, the value variable takes on the value of the next value in the list.

In the third loop, we are iterating over both keys and values of the dictionary using the items() method.

This method returns a list of tuples, where each tuple contains a key-value pair.

In each iteration, the key and value variables take on the values of the next tuple in the list.


Conclusion

Iterating over dictionaries in Python is a common task that can be done using a for loop.

We can iterate over the keys, values, or both keys and values of a dictionary using the appropriate method.

By using these techniques, we can easily access and manipulate the data stored in a dictionary in our Python programs.