在Python中,可以使用for循环来遍历字典。有几种常用的方法可以遍历字典的键、值或键值对:
my_dict = {"a": 1, "b": 2, "c": 3}
for key in my_dict:
print(key)
输出:
a
b
c
my_dict = {"a": 1, "b": 2, "c": 3}
for value in my_dict.values():
print(value)
输出:
1
2
3
my_dict = {"a": 1, "b": 2, "c": 3}
for key, value in my_dict.items():
print(key, value)
输出:
a 1
b 2
c 3
还可以使用内置的iter()
函数结合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
输出:
a
b
c
1
2
3
以上是遍历字典的几种常见方法,根据具体情况选择合适的方法进行遍历。