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. Atitit eclipse新特性总结3.1---4.4  4.5

    Atititeclipse新特性总结3.1---4.4  4.5 1. Eclipse 4.4 Luna正式发布了.1 1.1. 新版本的Eclipse默认对Java8提供支持1 1.2. 内存分析器 ...

  2. HDU - 5301 Buildings

    Buildings Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others) Total S ...

  3. file、inode在应用层和驱动层之间的联系_转

    转自:http://blog.csdn.net/dreaming_my_dreams/article/details/8272586 应用层和驱动的衔接,一直是一个老大难问题,若弄不清楚,总觉得驱动写 ...

  4. 2016ATF阿里巴巴技术论坛

    转自:http://blog.csdn.net/mini_monster/article/details/51175879 “爱迪生的贡献不在于让灯泡亮的更久一些,爱迪生最大的贡献是在全世界第一个想到 ...

  5. Redis Scan的使用方式以及Spring redis的坑

    SpringRedisTemplate针对这个Scan进行了封装,示例使用(针对最新库spring-data-redis-1.8.1.RELEASE): Set<Object> execu ...

  6. 基于springCloud的分布式架构体系

    Spring Cloud作为一套微服务治理的框架,几乎考虑到了微服务治理的方方面面,之前也写过一些关于Spring Cloud文章,主要偏重各组件的使用,本次分享主要解答这两个问题:Spring Cl ...

  7. java中JSONObject与JSONArray的使用

    JSONObject与JSONArray 最近在学习过程中用到了稍微复杂点的json数据需要将json数据解析出来,这里就截取一部分作为例子 1.JSONObject介绍 JSONObject-lib ...

  8. python 函数 参数 (难点传入dict list)

    --使用参数组可以传值列表,字典:格式 #-*-coding:utf-8-*- def func5(x,*s,**gs): print(x) print(s) print(gs) print '*'* ...

  9. WPF TextBox 验证输入

    //验证输入为数字private void txt_time_KeyDown(object sender, KeyEventArgs e){ if (!((e.Key >= Key.D0 &am ...

  10. Week 3: Assessing performance 笔记

    得到一个模型之后如何评价其性能? training error & generalization error & test error 如何理解generalization error ...