系统:Windows 7
语言版本:Anaconda3-4.3.0.1-Windows-x86_64
编辑器:pycharm-community-2016.3.2
- 这个系列讲讲Python对字典的一些实用操作
- 本文介绍:如何对字典进行遍历操作
Part 1:示例说明
- 已知字典
dict_a = {'a': 1, 'b': 2, 'c': 3}
,对其进行遍历获取其元素
Part 2:遍历
-
for ele in dict_a
,对键进行遍历 -
for ele in dict_a.items()
,对字典内每一对进行遍历 -
for ele in dict_a.keys()
,对键进行遍历 -
for ele in dict_a.values()
,对值进行遍历
Part 3:代码
dict_a = {'a': 1, 'b': 2, 'c': 3}
print(dict_a)
print('\n')
print('默认对键进行遍历')
for ele in dict_a:
print(ele)
print(type(ele))
print('\n')
print('输出每一个字典元素,元组')
for ele in dict_a.items():
print(ele)
print(type(ele))
print('\n')
print('对键进行遍历')
for ele in dict_a.keys():
print(ele)
print(type(ele))
print('\n')
print('对值进行遍历')
for ele in dict_a.values():
print(ele)
print(type(ele))
print('\n')
代码截图

输出结果

Part 4:部分代码解读
-
print(type(ele))
输出变量数据类型 -
for ele in dict_a.items()
中输出的每个元素将原来的字典转换为元组,键为第一个元素,值为第2个元素,如下图所示
元组输出

本文为原创作品,欢迎分享朋友圈
长按图片识别二维码,关注本公众号
Python 优雅 帅气

网友评论