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)存储,具有极快的查找速度. 举个例 ...
随机推荐
- fpga技能树
- sendmail发件人邮箱设定命令
sendmail发件人邮箱设定命令 以前就碰到过设置发件人后缀的方式,这次迁移服务器居然忘记,从头开始记录下 1:第一种方法,修改/etc/hosts,据说sendmail使用hosts里面的本地 ...
- crontab用法
在工作中有时需要定时执行某些操作,于是想到使用crontab来实现 crontab的用法: crontab file [-u user] 用指定的文件替代目前的crontab crontab - ...
- Kafka具体解释五、Kafka Consumer的底层API- SimpleConsumer
1.Kafka提供了两套API给Consumer The high-level Consumer API The SimpleConsumer API 第一种高度抽象的Consumer API,它使用 ...
- 虚拟化笔记05 OpenFiler configuration
5.OpenFiler configuration 登录Openfiler 步骤1:安装 FireFox 步骤2:通过FireFox以HTTPS://server-ip:446 远程访问OpenFil ...
- Xshell配色方案(Solarized Dark)
将以下内容复制并保存到文件中,文件名以xc为后缀,如:Solarized Dark.xcs [Solarized Dark] text= cyan(bold)=93a1a1 text(bold)= m ...
- [浪风转载]Jquery取得iframe中元素的几种方法
iframe在复合文档中经常用到,利用jquery操作iframe可以大幅提高效率,这里收集一些基本操作 DOM方法:父窗口操作IFRAME:window.frames["iframeSon ...
- (转载)Unity中解析ini配置文件----INIParser
大家好,我是孙广东. 转载请注明出处:http://blog.csdn.net/u010019717 更全的内容请看我的游戏蛮牛地址:http://www.unitymanual.com/spac ...
- package-cleanup用法
今天升级时候遇到"you could try using package-cleanup --problems to work around the problem ...", 本 ...
- ios --图片文字组合头像那点事
/** 图片文字组合头像那点事 @param string 昵称 @param imageSize 图片尺寸 @param imageColor 图片颜色 @return 返回的 图片 */ + (U ...