Python Dictionary Iteration Methods

In Python, you can use a for loop to iterate over a dictionary. There are several common methods to iterate over the keys, values, or key-value pairs of a dictionary.

  1. Iterate through the keys of the dictionary.
my_dict = {"a": 1, "b": 2, "c": 3}
for key in my_dict:
    print(key)

Output:

a
b
c
  1. Iterating through the values of a dictionary:
my_dict = {"a": 1, "b": 2, "c": 3}
for value in my_dict.values():
    print(value)

Output:

1
2
3
  1. Iterating over key-value pairs in a dictionary:
my_dict = {"a": 1, "b": 2, "c": 3}
for key, value in my_dict.items():
    print(key, value)

Output:

a 1
b 2
c 3

You can also iterate over a dictionary’s keys or values using the built-in iter() function combined with next().

my_dict = {"a": 1, "b": 2, "c": 3}
my_dict_iter = iter(my_dict)

# 遍历字典的键
while True:
    try:
        key = next(my_dict_iter)
        print(key)
    except StopIteration:
        break

# 遍历字典的值
my_dict_iter = iter(my_dict.values())
while True:
    try:
        value = next(my_dict_iter)
        print(value)
    except StopIteration:
        break

Output:

a
b
c
1
2
3

Here are several common ways to iterate through a dictionary, choose the appropriate method based on your specific situation.

bannerAds