Linux 拨号vps windows公众号手机端

python遍历字典的方法是什么

lewis 9年前 (2017-01-15) 阅读数 9 #程序编程
文章标签 python

在Python中,可以使用for循环来遍历字典。有几种常用的方法可以遍历字典的键、值或键值对:

  1. 遍历字典的键:
my_dict = {"a": 1, "b": 2, "c": 3}
for key in my_dict:
    print(key)

输出:

a
b
c
  1. 遍历字典的值:
my_dict = {"a": 1, "b": 2, "c": 3}
for value in my_dict.values():
    print(value)

输出:

1
2
3
  1. 遍历字典的键值对:
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

以上是遍历字典的几种常见方法,根据具体情况选择合适的方法进行遍历。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门