Python字典遍历操作实例小结

yipeiwu_com5年前Python基础

本文实例讲述了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相关内容感兴趣的读者可查看本站专题:《Python字典操作技巧汇总》、《Python列表(list)操作技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python学习笔记之While循环用法分析

本文实例讲述了Python学习笔记之While循环用法。分享给大家供大家参考,具体如下: 前面一篇《Python学习笔记之For循环用法》详细介绍了Python for循环,这里再来讲述...

python飞机大战 pygame游戏创建快速入门详解

python飞机大战 pygame游戏创建快速入门详解

本文实例讲述了python飞机大战 pygame游戏创建。分享给大家供大家参考,具体如下: 目标 项目准备 使用 pygame 创建图形窗口 理解 图像 并实现图像绘制...

python3+PyQt5使用数据库表视图

python3+PyQt5使用数据库表视图

上文提到窗体可以一次性呈现出来自同一记录的各个域,但是对于用户希望能看到多条记录的表来说,就需要使用表格化的视图了。本文通过python3+pyqt5改写实现了python Qt gui...

python导入模块交叉引用的方法

实际项目中遇到python模块相互引用问题,查资料,终于算是弄明白了。 首先交叉引用或是相互引用,实际上就是导入循环,关于导入循环的详细说明,可见我摘自《python核心编程》第二版的摘...

python求pi的方法

本文实例讲述了python求pi的方法,是一篇翻译自国外网站的文章,分享给大家供大家参考。 具体实现方法如下: #_*_ coding=utf-8 *_* ## {{{ http:/...