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)存储,具有极快的查找速度. 举个例 ...
随机推荐
- linux命名空间详解_转
转自: Linux的命名空间详解--Linux进程的管理与调度(二) Linux Namespaces机制提供一种资源隔离方案. PID,IPC,Network等系统资源不再是全局性的,而是属于特定的 ...
- 定时器(setTimeout/setInterval)调用带参函数失效解决方法
也许你曾碰到过这样的问题,不管是setInterval()还是setTimeout(),当code参数里放一个带参函数时,定时器都会失效,看下面这个例子: function test(str){ al ...
- atom安装插件
1. 由于墙的原因,在界面中安装不了 先安装 npm 可以下载node.js桌面版命令行 2.打开命令行中进入atom的安装目录,进入到packages 中 3. 进入github 官网 输入你要下载 ...
- plsql programming 20 管理PL/SQL代码(个人感觉用不到)
这一章的内容, 只完成了一部分, 剩下的用到再补充吧 由于依赖关系, 而编译失败, 需要重新编译. ( 所谓依赖, 是指存储过程, 函数等在运行中调用的对象, 比如table 等, 比如你删除了过程中 ...
- springmvc 环境配置图
- Web 层由 Web,Web-MVC,Web-Socket 和 Web-Portlet 组成
Web 层由 Web,Web-MVC,Web-Socket 和 Web-Portlet 组成,它们的细节如下: Web 模块提供面向web的基本功能和面向web的应用上下文,比如多部分(multipa ...
- postgresql学习文档
字符串函数: http://www.php100.com/manual/PostgreSQL8/functions-string.html http://gavin-chen.iteye.com/bl ...
- 【转】约瑟夫环算法---------题目:有n个人围成一圈,顺序排号,从第一个开始报数(从1到3报数),凡报到3的人退出圈子,问最后最后留下的是原来第几号的那位.
提示:用环形链表实现 对于这个题目其实就是用c语言的循环链表实现一个约瑟夫环.我们可以定义一个循环链表,将这n个人加入到链表中,然后定义三个节点指针在链表上循环,移动跨度为3,利用链表的循环功能每次删 ...
- std::condition_variable(复习)
#include <iostream> // std::cout #include <thread> // std::thread #include <mutex> ...
- linux下软件的安装与卸载
一 软件安装包的类型 通常Linux应用软件的安装有五种: 1) tar+ gz包,如software-1.2.3-1.tar.gz.他是使用UNIX系统的打包工具tar打包的. 2) r ...