Traverse the dict in Python
We usually use the following 2 ways to traverse a dict:
1: for d in dic 2: for d in dic.keys()
Which one is better? Let's have a look at one simple demo.
#!/usr/bin/python
dic = {'a': 1, 'b': 2, 'c': 1}
print(dic)
for d in dic:
if dic[d] == 1:
del(dic[d])
print(dic)
What we get is an RuntimeError: "dictionary changed size during iteration". Now let's try the 2nd method as follows.
#!/usr/bin/python
dic = {'a': 1, 'b': 2, 'c': 1}
print(dic)
# dic.keys() is recommended.
#for d in dic: # NOT OK #RuntimeError: dictionary changed size during iteration
for d in dic.keys(): # OK
if dic[d] == 1:
del(dic[d])
print(dic)
And we got the expected result.
Let's take a simple analysis: in the 1st demo code, the target we traverse is the dict itself, and we delete
the first element whose value is 1 in the iteration, so the dictionary(target we traverse)'s size is changed
during the iteration, then we get the RuntimeError. While in the 2nd demo code, the target we traverse is not
the dict itself but the dic.keys() --which is ['a', 'b', 'c'], so during the iteration the size of the target is not
changed.
So, maybe we could draw the conclusion that sometimes(when we modify the dict during the traversing)
the 2nd method to traverse a dict is safer than the 1st one.
Update:
For Python3.+ the 1st demo code does NOT work, and we still got the error message "RuntimeError: dictionary changed size during iteration".
> In Python3.+ we need to use `for k in list(mydict.keys())`:as Python3.+ makes the `keys()` method an iterator, and also disallows
> deleting dict items during iteration. By adding a `list()` call we turn the `keys()` iterator into a list. So when we are in the body of the for loop we
> are no longer iterating over the dictionary itself.
References:
python编程细节──遍历dict的两种方法比较: http://blogread.cn/it/article/2438?f=sr
How to delete items from a dictionary while iterating over it? https://stackoverflow.com/questions/5384914/how-to-delete-items-from-a-dictionary-while-iterating-over-it
Traverse the dict in Python的更多相关文章
- 【LeetCode】498. Diagonal Traverse 解题报告(Python)
[LeetCode]498. Diagonal Traverse 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: htt ...
- Python中内置数据类型list,tuple,dict,set的区别和用法
Python中内置数据类型list,tuple,dict,set的区别和用法 Python语言简洁明了,可以用较少的代码实现同样的功能.这其中Python的四个内置数据类型功不可没,他们即是list, ...
- Python中list,tuple,dict,set的区别和用法
Python语言简洁明了,可以用较少的代码实现同样的功能.这其中Python的四个内置数据类型功不可没,他们即是list, tuple, dict, set.这里对他们进行一个简明的总结. List ...
- python基础——使用dict和set
python基础——使用dict和set dict Python内置了字典:dict的支持,dict全称dictionary,在其它语言中也称为map(映射),使用键-值(key-value)存储,具 ...
- python 使用dict和set
dict Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度. 举个例子,假设要根据同学的名字 ...
- Python中dict详解
from:http://www.cnblogs.com/yangyongzhi/archive/2012/09/17/2688326.html Python中dict详解 python3.0以上,pr ...
- python中的字典(dict),列表(list),元组(tuple)
一,List:列表 python内置的一种数据类型是列表:list.list是一种有序的数据集合,可以随意的添加和删除其中的数据.比如列出班里所有的同学的名字,列出所有工厂员工的工号等都是可以用到列表 ...
- Python字典(dict)使用技巧
字典dict是Python中使用频率非常高的数据结构,关于它的使用,也有许多的小技巧,掌握这些小技巧会让你高效地的使用dict,也会让你的代码更简洁. 1.默认值 假设name_for_userid存 ...
- python入门(12)dict
python入门(12)dict Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度. 举个例 ...
随机推荐
- TBS 手册 --phpv 翻译
为何使用它? 示例 下载 手册 支持 论坛 推荐 秀出你的站点 http://phpv.net/TBS_Manual.htm#html_automatic 网站: http://www.tinybut ...
- 李洪强漫谈iOS开发[C语言-002]-开发概述程序的本质与简单执行过程
李洪强iOS开发之应用程序的本质与简单执行过程 什么叫程序? 就是一段执行指令 程序的两个状态: 保存状态(保存到硬盘上) 运行状态(由CPU执行) 代码可以执行吗? CPU(中央处理器-> ...
- 推荐个强大的任务管理器-Process Hacker
软件主页及下载: http://processhacker.sourceforge.net/index.php 之前一直用process explorer 功能一样强大,但是process hacke ...
- linux list
一篇介绍链表不错的文章: 1. 玩转C链表 2. openwrt使用list 3. 深入分析 Linux 内核链表 https://www.ibm.com/developerworks/cn/linu ...
- npm安装vue-cil出现错误
这个错误有点尴尬..... 之前全局安装过cil,然后在全局安装出现了这个错误,各种手册看了半天也没有头绪,猛然想起来之前安装过,试下直接初始化项目试一下,果然成功了 然后在 npm install ...
- easyui data-options的使用
easyui data-options的使用 data-options是jQuery Easyui 最近两个版本才加上的一个特殊属性.通过这个属性,我们可以对easyui组件的实例化可以完全写入到ht ...
- Eclipse 透视图(Perspective)
什么是透视图? 透视图是一个包含一系列视图和内容编辑器的可视容器.默认的透视图叫 java. Eclipse 窗口可以打开多个透视图,但在同一时间只能有一个透视图处于激活状态. 用户可以在两个透视图之 ...
- python XML基础
什么是XML XML 指可扩展标记语言(EXtensible Markup Language) XML 是一种标记语言,很类似 HTML XML 的设计宗旨是传输数据,而非显示数据 XML 的标签需要 ...
- android studio win7开发环境
java 开发环境 这里使用jdk1.7版本,从官网上下载. 点击.正常的window软件的安装方式,一直下一步即可. 环境变量的设置: 在系统属性中,对需要的环境变量进行设置: JAVA_HOME设 ...
- JAVA的protected权限
1.派生类能够訪问父类的protected数据.这是毫无疑问的. 2.今天做Think in java的习题发现,同一个包内的一个类调用还有一个类的protected数据是能够的.代码例如以下: pa ...