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. 使用apxs安装apache模块

    使用apxs安装apache模块                 ---by石锅拌饭 1.缘由 前几天迁移系统.发现配置了fastcgi的一个脚本下载文件总是提示类似Connection reset ...

  2. Redis命令学习-string类型操作

    APPEND key value     假设key已经存在,而且为字符串.那么这个命令会把value追加到原来值的末尾.假设key不存在.首先创建一个空字符串,再运行追加操作.     返回值:返回 ...

  3. Mysql又一次整理笔记--woods备忘

    ==============================SQL备忘 CRUD 查询 多表 事件等=============================== ------------------ ...

  4. JPA动态查询封装

    一.定义一个查询条件容器 /** * 定义一个查询条件容器 * * @param <T> */ public class Criteria<T> implements Spec ...

  5. Spring MVC下拉选项(Select)

    以下示例显示如何在使用Spring Web MVC框架的表单中使用下拉选项(Dropdown).首先使用Eclipse IDE来创建一个WEB工程,实现一个让用户可选择自己所在的国家的功能.并按照以下 ...

  6. What is special about /dev/tty?

    ls -la /dev/tty shows the output: crw-rw-rw- 1 root tty 5, 0 Dec 14 22:21 /dev/tty The 'c' means it' ...

  7. Linux 超级守护进程 xinetd

    在Linux中,守护进程有两种方式,一种是svsy方式,一种是xinetd方式(超级守护进程). 每个守护进程都会有一个脚本,可以理解成工作配置文件,守护进程的脚本需要放在指定位置,独立启动守护进程: ...

  8. 45、Android事件总线分发库的使用

    事件总线分发库EventBus和Otto的简介及对比 什么是事件总线管理: a.将事件放到队列里,用于管理和分发b.保证应用的各个部分之间高效的通信及数据.事件分发c.模块间解耦 Event Bus是 ...

  9. 【BZOJ2286】[Sdoi2011]消耗战 虚树

    [BZOJ2286][Sdoi2011]消耗战 Description 在一场战争中,战场由n个岛屿和n-1个桥梁组成,保证每两个岛屿间有且仅有一条路径可达.现在,我军已经侦查到敌军的总部在编号为1的 ...

  10. IIPP迷你项目(二)"Guess the Number!"

    本来这个程序是早就编完了的,一直没时间发布博客.时至今日已时隔多天,也算是复习一下事件驱动型编程的过程吧. 1 事件驱动型编程 本质上这次的作业是披着猜数字皮的图形化界面编程,好在 simplegui ...