How to use a for loop to iterate through a dictionary in Python?

In Python, you can use a for loop to iterate through a dictionary. There are two common methods:

  1. Iterate through the keys of the dictionary.
my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}

for key in my_dict:
    print(key, my_dict[key])

Output:

key1 value1
key2 value2
key3 value3
  1. Iterating through key-value pairs in a dictionary.
my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}

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

Output:

key1 value1
key2 value2
key3 value3

In the second method, the items() method is used to access the key-value pairs of a dictionary, and two variables are used to store the key and value separately.

bannerAds