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的更多相关文章

  1. 【LeetCode】498. Diagonal Traverse 解题报告(Python)

    [LeetCode]498. Diagonal Traverse 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: htt ...

  2. Python中内置数据类型list,tuple,dict,set的区别和用法

    Python中内置数据类型list,tuple,dict,set的区别和用法 Python语言简洁明了,可以用较少的代码实现同样的功能.这其中Python的四个内置数据类型功不可没,他们即是list, ...

  3. Python中list,tuple,dict,set的区别和用法

    Python语言简洁明了,可以用较少的代码实现同样的功能.这其中Python的四个内置数据类型功不可没,他们即是list, tuple, dict, set.这里对他们进行一个简明的总结. List ...

  4. python基础——使用dict和set

    python基础——使用dict和set dict Python内置了字典:dict的支持,dict全称dictionary,在其它语言中也称为map(映射),使用键-值(key-value)存储,具 ...

  5. python 使用dict和set

    dict Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度. 举个例子,假设要根据同学的名字 ...

  6. Python中dict详解

    from:http://www.cnblogs.com/yangyongzhi/archive/2012/09/17/2688326.html Python中dict详解 python3.0以上,pr ...

  7. python中的字典(dict),列表(list),元组(tuple)

    一,List:列表 python内置的一种数据类型是列表:list.list是一种有序的数据集合,可以随意的添加和删除其中的数据.比如列出班里所有的同学的名字,列出所有工厂员工的工号等都是可以用到列表 ...

  8. Python字典(dict)使用技巧

    字典dict是Python中使用频率非常高的数据结构,关于它的使用,也有许多的小技巧,掌握这些小技巧会让你高效地的使用dict,也会让你的代码更简洁. 1.默认值 假设name_for_userid存 ...

  9. python入门(12)dict

    python入门(12)dict Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度. 举个例 ...

随机推荐

  1. 从DTS到驱动加载的过程分析

    http://blog.csdn.net/iefswang/article/details/40543733 http://www.linuxidc.com/Linux/2013-07/86839.h ...

  2. Linux下同步模式、异步模式、阻塞调用、非阻塞调用总结

    转自:http://www.360doc.com/content/13/0117/12/5073814_260691714.shtml 同步和异步:与消息的通知机制有关. 本质区别 现实例子 同步模式 ...

  3. c++ about SLL(Static-Link Library) and DLL(Dynamic-Link Library)

    First thing first, Wiki: http://en.wikipedia.org/wiki/Dynamic-link_library http://en.wikipedia.org/w ...

  4. python 开发技巧(4)-- 用PyCharm实用技巧(我自己常用的)

    pycharm快捷键 1.快速导入类 Ctrl + Alt + Space 2.追踪类和方法的定义 Ctrl + b 3.复制当前行 Ctrl + d 4.移动当前行 Ctrl + Shift + ( ...

  5. Oracle----Oracle 11g XE release2安装与指导

    今天上午我安装了Oracle 11g企业版,发现太占内存了,考虑到MS SQL有express版本,所以寻思着尝试尝试Oracle 11g的express版本,就是EX版本.下面是具体的安装步骤. 1 ...

  6. 008android初级篇之jni中数组的传递

    008android初级篇之jni中数组的传递 jni中在native中数据类型的实际类型 jchar 占两个字节,跟native c中的char(占一个字节)是两个数据类型 jbyte, unsig ...

  7. c# 扩展方法奇思妙用基础篇八:Distinct 扩展

    刚看了篇文章 <Linq的Distinct太不给力了>,文中给出了一个解决办法,略显复杂. 试想如果能写成下面的样子,是不是更简单优雅 var p1 = products.Distinct ...

  8. poj 2125(最小割)

    题目链接:http://poj.org/problem?id=2125 思路:将最小点权覆盖转化为最小割模型,于是拆点建图,将点i拆成i,i+n,其中vs与i相连,边容量为w[i]-,i+n与vt相连 ...

  9. OpenCV学习笔记十五:opencv_features2d模块

    一,简介: 该库用于2D特征检测,描述与匹配.

  10. gcc 编译 连接 生成可执行文件

    gcc c语言编译器 g++ c++编译器 gcc a.c  生成默认的a.out 可执行文件  ./a.out  来执行 gcc -c a.c 编译生成 a.o 目标文件 可以检查语法错误 gcc ...