How to Iterate over a Dictionary in Python

Here are 3 ways to iterate over a dictionary in Python:

(1) Iterate over the keys of a dictionary:

for key in my_dict.keys():
print(key)

(2) Iterate over the values of a dictionary:

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

(3) Iterate over both the keys and values of a dictionary:

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

Examples of Iterating over a Dictionary in Python

Example 1: Iterate over the keys of a dictionary

In the following example, the keys of a simple dictionary would be printed:

my_dict = {1: "blue", 2: "green", 3: "red", 4: "yellow", 5: "orange"}

for key in my_dict.keys():
print(key)

Here are the keys that you’ll get after iterating over the dictionary:

1
2
3
4
5

Example 2: Iterate over the values of a dictionary

Next, the values of a dictionary would be printed:

my_dict = {1: "blue", 2: "green", 3: "red", 4: "yellow", 5: "orange"}

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

As you can see, the values of the dictionary are now printed:

blue
green
red
yellow
orange

Example 3: Iterate over both the keys and values of a dictionary

Here, both the keys and values of a dictionary would be printed:

my_dict = {1: "blue", 2: "green", 3: "red", 4: "yellow", 5: "orange"}

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

The result:

1 blue
2 green
3 red
4 yellow
5 orange

Iterating over a dictionary, and saving the results in a new dictionary

To iterate over a dictionary, and then save the results in a new dictionary (called new_dict), where each key would be incremented by 1:

my_dict = {1: "blue", 2: "green", 3: "red", 4: "yellow", 5: "orange"}

new_dict = {}

for key, value in my_dict.items():
new_dict[key + 1] = value

print(new_dict)

As you can see, the keys of the new dictionary are now incremented by 1 (compared to the original dictionary):

{2: 'blue', 3: 'green', 4: 'red', 5: 'yellow', 6: 'orange'}

Finally, increment each key by 1, and also add the word ‘color’ after each value:

my_dict = {1: "blue", 2: "green", 3: "red", 4: "yellow", 5: "orange"}

new_dict = {}

for key, value in my_dict.items():
new_dict[key + 1] = value + " color"

print(new_dict)

The result:

{2: 'blue color', 3: 'green color', 4: 'red color', 5: 'yellow color', 6: 'orange color'}

Leave a Comment