温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python中怎么实现字典遍历操作

发布时间:2021-06-16 17:30:31 来源:亿速云 阅读:196 作者:Leah 栏目:开发技术

这篇文章将为大家详细讲解有关Python中怎么实现字典遍历操作,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

1 遍历键值对

可以使用一个 for 循环以及方法 items() 来遍历这个字典的键值对。

dict = {'evaporation': '蒸发',
    'carpenter': '木匠'}
for key, value in dict.items():
  print('key=' + key)
  print('value=' + value)

运行结果:

key=evaporation
value=蒸发
key=carpenter
value=木匠

key、value 这两个变量可以任意命名,比如下面的这个示例使用了 word 与 explain:

dict = {'evaporation': '蒸发',
    'carpenter': '木匠'}
for word, explain in dict.items():
  print('word=' + word)
  print('explain=' + explain)

运行结果:

word=evaporation
explain=蒸发
word=carpenter
explain=木匠

良好的命名习惯,可以编写出让人更容易理解的代码。

2 遍历键

使用方法 keys() ,可以遍历字典中的键。

dict = {'evaporation': '蒸发',
    'carpenter': '木匠'}
for word in dict.keys():
  print(word.title())

运行结果:

Evaporation
Carpenter

因为遍历字典时, 会默认遍历所有的键。所以,我们可以省略方法 keys() 。

for word in dict:
  print(word.title())

运行结果与上一示例相同。

方法 keys() 还可以用在条件表达式中,用于判断 key 在字典中是否存在。

dict = {'evaporation': '蒸发',
    'carpenter': '木匠'}
print('carpenter' in dict)

运行结果:

True

3 按顺序遍历键

可以在 for 循环中对返回的键进行排序,可以使用 sorted() 函数。

dict = {'evaporation': '蒸发',
    'carpenter': '木匠'}
for word in sorted(dict):
  print('word:' + word)

运行结果:

word:carpenter
word:evaporation

4 遍历值

可使用 values() 方法来遍历字典的值。

dict = {'evaporation': '蒸发',
    'carpenter': '木匠'}
for explain in dict.values():
  print('explain:' + explain)

运行结果:

explain:蒸发
explain:木匠

有时候需要返回不重复的值。这时,我们可以使用集合( set) 。 集合类似于列表, 但它所包含的每个元素,都必须是独一无二的。

dict = {'evaporation': '蒸发',
    'carpenter': '木匠',
    'millman': '木匠'}
print('【包含重复】' + str(dict.values()))
print('【剔除重复】' + str(set(dict.values())))

运行结果:

【包含重复】dict_values(['蒸发', '木匠', '木匠'])
【剔除重复】{'蒸发', '木匠'}

**注意:**字典的 values() 的字符串化与 set() 不同。

关于Python中怎么实现字典遍历操作就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI