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. NGINX扩展

    https://github.com/cuber/ngx_http_google_filter_module

  2. mysql workbench 导出表结构

    Server->Data Export 选择数据库(我的是 lhc库) -> 选择对应表(我的是  device表), Dump Structre and Data 导出表数据和表结构 D ...

  3. mock异常

    在类开始的时候: @Rule public ExpectedException expectedEx = ExpectedException.none(); 在方法中执行下面代码: expectedE ...

  4. SQL : IN 和 Exists 的区别

    Sql语句中IN和exists的区别及应用 表展示 首先,查询中涉及到的两个表,一个user和一个order表,具体表的内容如下: user表: order表: in 确定给定的值是否与子查询或列表中 ...

  5. Ultra-QuickSort - poj 2299 (归并排序+统计逆序数)

    利用归并排序统计逆序数,利用归并求逆序在对子序列s1和s2在归并时(s1,s2已经排好序),若s1[i]>s2[j](逆序状况),则逆序数加上s1.length-i,因为s1中i后面的数字对于s ...

  6. android中通过代码来设置蓝牙永久可见性

    废话不多说,直接阐述: 前段时间在搞一个android项目,其中有一个功能要求需要蓝牙可见性永久打开,但是开发过android蓝牙的程序员应该都知道,goole提供的api中没有设置蓝牙永久可见性的接 ...

  7. MD5摘要(Java实现)

    消息摘要算法又成散列算法,其核心在于散列函数的单向性.即通过散列函数可获得对应的散列值,但不可以通过散列值反推其原始信息.   消息摘要算法分为以下三大类:       MD(Message Dige ...

  8. Java并发计数器探秘

    前言 一提到线程安全的并发计数器,AtomicLong 必然是第一个被联想到的工具.Atomic* 一系列的原子类以及它们背后的 CAS 无锁算法,常常是高性能,高并发的代名词.本文将会阐释,在并发场 ...

  9. Windows中搭建ftp服务器

    使用工具Quick Easy FTP Server Windows中搭建FTP服务器有什么用呢? 确实没有用,直到有一次,我在VM中安装了Linux虚拟机,但是文件怎么也上传不到这个虚拟机中. 然后用 ...

  10. java 读取world的图片 并把图片路径存入数据库

    package World; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundExcep ...