python 循环遍历字典元素
来源:互联网 发布:介绍人工智能的文章 编辑:程序博客网 时间:2024/06/01 17:47
一个简单的for语句就能循环字典的所有键,就像处理序列一样:
In [1]: d = {'x':1, 'y':2, 'z':3}
In [2]: for key in d:
...: print key, 'corresponds to', d[key]
...:
y corresponds to 2
x corresponds to 1
z corresponds to 3
在python2.2之前,还只能用beys等字典方法来获取键(因为不允许直接迭代字典)。如果只需要值,可以使用d.values代替d.keys。d.items方法会将键-值对作为元组返回,for循环的一大好处就是可以循环中使用序列解包:
In [4]: for key, value in d.items():
...: print key, 'corresponds to', value
...:
y corresponds to 2
x corresponds to 1
z corresponds to 3
注意:字典元素的顺序通常没有定义。换句话说,迭代的时候,字典中的键和值都能保证被处理,但是处理顺序不确定。如果顺序很重要的话,可以将键值保存在单独的列表中,例如迭代前进行排序。
0 0
- python 循环遍历字典元素
- python循环遍历字典元素
- Python -- 遍历字典时删除元素报异常
- python遍历字典
- Python 字典结构遍历
- Python学习-字典遍历
- python中的字典遍历
- Python: 遍历字典
- python字典遍历
- python 字典遍历
- Python 遍历字典
- Python 字典遍历
- python 字典 添加元素
- python 字典元素删除
- ArrayList循环遍历删除元素
- python遍历删除字典里值为空的元素报错
- swift-for循环遍历,遍历字典,循环生成数组
- Python循环遍历文件
- 我理解的大小端存储
- hdu find the max(1594)
- 【算法学习笔记】11.数据结构基础 二叉树初步练习4
- EasyUI datagrid默认选中第一行
- HDU 4891 The Great Pan 模拟
- python 循环遍历字典元素
- 在ISE下分析和约束时序
- 熵编码--mpeg12video huffman编码
- HDU 1114 Piggy-Bank 完全背包的变形
- MFC生成Win7或XP风格
- Jboss 远程调试
- hdu 4737A Bit Fun
- easyUI-datagrid 点击触发check事件
- STL迭代器