python中遍历字典的操作
一个python字典可能只包含几个键值对,也可能包含数量庞大的键值对。鉴于字典可能包含大量的数据,python支持对字典遍历。
一、遍历所有的键值对
使用for循环来遍历字典。但是遍历字典时,键值对的返回顺序也与存储顺序不同。在python不关心键值对的存储顺序,它只跟踪键和值的关联关系。
实例:(使用items()方法,将键与值分别赋值给变量key和value.)
![9f505153dc30df5112f313ea6cac8bcf.png](https://img-blog.csdnimg.cn/img_convert/9f505153dc30df5112f313ea6cac8bcf.png)
结果:
![66e19c22b07edf6d3e5068208b89a6e6.png](https://img-blog.csdnimg.cn/img_convert/66e19c22b07edf6d3e5068208b89a6e6.png)
二、遍历所有的键
使用keys()方法,可以提取字典中的所有键。
实例:
![59db1c9aa304280f57d4e97ef15b6743.png](https://img-blog.csdnimg.cn/img_convert/59db1c9aa304280f57d4e97ef15b6743.png)
结果:
![aac335a18619693c5a90f202b23c5cc5.png](https://img-blog.csdnimg.cn/img_convert/aac335a18619693c5a90f202b23c5cc5.png)
三、遍历字典中的所有值
使用values()方法,它返回一个值列表,而不包含任何键。这种做法提取字典中的所有值,而没有考虑值是否重复。
实例:
![f770ef5322b7d12a7c89c005eaa7da37.png](https://img-blog.csdnimg.cn/img_convert/f770ef5322b7d12a7c89c005eaa7da37.png)
结果:
![fb0364490faa1496c3d0bc05f3bec80a.png](https://img-blog.csdnimg.cn/img_convert/fb0364490faa1496c3d0bc05f3bec80a.png)
对于使用set()方法,可以获得一个值不重复的列表。
实例:
![bed06c46829cd9aceee55a61e07d8630.png](https://img-blog.csdnimg.cn/img_convert/bed06c46829cd9aceee55a61e07d8630.png)
结果:
![648daa3e4293c2b99e09f6cab053b244.png](https://img-blog.csdnimg.cn/img_convert/648daa3e4293c2b99e09f6cab053b244.png)
四、嵌套
有时候,需要将一系列字典存储在列表中,或将列表作为字典中的值存储在字典中,这就被称之为嵌套。
1、 字典列表、
实例:
![ea9d4ddb8c8240fb6a28d60f4b8e324a.png](https://img-blog.csdnimg.cn/img_convert/ea9d4ddb8c8240fb6a28d60f4b8e324a.png)
结果:
![f7c63cf1b2245175c793b1b21ac98e9b.png](https://img-blog.csdnimg.cn/img_convert/f7c63cf1b2245175c793b1b21ac98e9b.png)
2、 在字典中存储列表
实例:
![e6c08d3295fae2c32e4baa5469e8750c.png](https://img-blog.csdnimg.cn/img_convert/e6c08d3295fae2c32e4baa5469e8750c.png)
结果:
![b67e8547e5dcdce24c32294afea85810.png](https://img-blog.csdnimg.cn/img_convert/b67e8547e5dcdce24c32294afea85810.png)
3、 在字典中存储字典
实例:
![1fa83b3b6381dd7d5d5996e2b6caa7b6.png](https://img-blog.csdnimg.cn/img_convert/1fa83b3b6381dd7d5d5996e2b6caa7b6.png)
结果:
![d0aa42911ba21b8c5ebe7dd9531d0118.png](https://img-blog.csdnimg.cn/img_convert/d0aa42911ba21b8c5ebe7dd9531d0118.png)
结束语:坚持就是胜利。坚持学习的姿态会感动自己,温暖他人。