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)存储,具有极快的查找速度. 举个例 ...
随机推荐
- Atitit.nosql api 标准化 以及nosql数据库的实现模型分类差异
Atitit.nosql api 标准化 以及nosql数据库的实现模型分类差异 1. 常用的nosql数据库MongoDB Cassandra1 1.1. 查询> db.blogposts. ...
- css制作的61种图像
HTML: <!DOCTYPE html> <html> <head> <title>css各种形状</title> <link re ...
- C++语言基础(13)-抽象类和纯虚函数
一.基本语法 在C++中,可以将虚函数声明为纯虚函数,语法格式为: ; 纯虚函数没有函数体,只有函数声明,在虚函数声明的结尾加上=0,表明此函数为纯虚函数. 最后的=0并不表示函数返回值为0,它只起形 ...
- 谱聚类python实践
聚类后: # -*- coding: utf-8 -*-"""Created on 09 05 2017 @author: similarface"" ...
- Android中*_handle_t/ANativeWindowBuffer/ANativeWindow/GraphicBuffer/Surface的关系
在阅读SurfaceFlinger HardwareComposer以及gralloc相关代码的过程中,我们经常会遇到native_handle private_handle_t ANativeWin ...
- Spring MVC简单URL处理程序映射
以下示例显示如何使用Spring Web MVC框架来实现一个简单URL处理程序映射. SimpleUrlHandlerMapping类分别显式地将URL映射到相应的控制器上. 所下所示配置 - &l ...
- ASP.NET:把ashx写到类库里并在页面上调用的具体方法
在类库中建Http Handler的操作很简单,就是添加一个普通的类,然后把之前ashx里的代码几乎一模一样贴到这个类中.但要注意命名空间和类名,因为之后我们会用 到.样例Handler: names ...
- Handler机制原理
andriod提供了Handler 和 Looper 来满足线程间的通信.Handler先进先出原则.Looper类用来管理特定线程内对象之间的消息交换(MessageExchange). 1)Loo ...
- Java 基础巩固:装箱拆箱 你真的熟悉吗
先考两道题: Integer a1 = 300; Integer a2 =300; System.out.print(a1 == a2); Integer b1 = 1; Integer b2 = 1 ...
- fzu2181(点的双连通分量+求奇环)
求出每个点双连通分量,如果在一个点双连通分量中有奇环,则这个分量每个点都在一个奇环中. 关键是要知道怎么求点双连通分量以及点双连通的性质. fzu2181 http://acm.fzu.edu.cn ...