Python遍历字典删除元素

这种方式是一定有问题的:

d = {‘a‘:1, ‘b‘:2, ‘c‘:3}
for key in d:
	d.pop(key)

会报这个错误:RuntimeError: dictionary changed size during iteration



这种方式Python2可行,Python3还是报上面这个错误。

d = {‘a‘:1, ‘b‘:2, ‘c‘:3}
for key in d.keys():
	d.pop(key)


Python3报错的原因是keys()函数返回的是dict_keys而不是list。Python3的可行方式如下:

d = {‘a‘:1, ‘b‘:2, ‘c‘:3}
for key in list(d):
	d.pop(key)

参考:How to avoid “RuntimeError: dictionary changed size during iteration” error?

*** walker ***

时间: 2024-12-11 01:38:09

Python遍历字典删除元素的相关文章

java 集合遍历时删除元素

本文探讨集合在遍历时删除其中元素的一些注意事项,代码如下 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 import java.util.ArrayList; import java.util.Iterator; import java

Java HashMap 如何正确遍历并删除元素

(一)HashMap的遍历 HashMap的遍历主要有两种方式: 第一种采用的是foreach模式,适用于不需要修改HashMap内元素的遍历,只需要获取元素的键/值的情况. HashMap<K, V> myHashMap; for (Map.entry<K, V> item : myHashMap.entrySet()){ K key = item.getKey(); V val = item.getValue(); //todo with key and val //WARNI

python 遍历字典

dict={"a":"apple","b":"banana","o":"orange"} print "##########dict######################" for i in dict: print "dict[%s]=" % i,dict[i] print "###########items############

Python 字典删除元素clear、pop、popitem

原文网站:http://www.iplaypython.com/jinjie/jj116.html 同其它python内建数据类型一样,字典dict也是有一些实用的操作方法.这里我们要说的是字典删除方法:clear().pop()和popitem(),这三种方法的作用不同,操作方法及返回值都不相同.接下来就来查看下这些字典特定方法的具体用法是什么. 字典clear()方法 clear()方法是用来清除字典中的所有数据,因为是原地操作,所以返回None(也可以理解为没有返回值) >>> x

python list遍历时删除元素

python list遍历时候删除还真需要注意下,今天帮同学处理数据,竟然傻逼了. 需求: 除了第一列,给每列加一个序号如:"1:0","2:0","3:20100307",然后删除冒号后为0的数据. 推荐做法: arrays = [ ['5001', '0', '0', '20100307', '20150109', '2', '3', '75', '0', '0', '114', '13', '2', '0', '0'], ['10001',

python遍历字典元素

a={'a':{'b':{'c':{'d':'e'}},'f':'g'},'h':'i'} def show(myMap): for str in myMap.keys(): secondDict=myMap[str] print str if type(myMap[str]).__name__=='dict': for key in secondDict.keys(): if type(secondDict[key]).__name__=='dict': print key show(seco

List的遍历和删除元素

/** * 遍历list的方法 * @param args */ public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("111"); list.add("222"); list.add("333"); list.add("222"); list.add("4

STL容器遍历时删除元素

STL容器遍历时在循环体内删除元素最容易出错了,根本原因都是因为迭代器有效性问题,在此记下通用删除方法,该方法适用于所有容器: 1 std::vector<int> myvec; 2 3 std::vector<int>::iterator it = myvec.begin(); 4 while( it != myvec.end()) 5 { 6 it = myvec.erase(it); 7 } 容器list有个比较另类的删除方法,如下代码所示: std::list<int

Python遍历字典的几种方式

“ 记录遍历字典的几种方式” 1 #遍历字典key值---方法1 2 for key in dict1: 3 print(key) 4 5 # 遍历字典key值---方法2 6 for key in dict1.keys(): 7 print(key) 8 9 #遍历字典value值 10 for value in dict1.values(): 11 print(value) 12 13 #遍历字典中的元素 14 for item in dict1.items(): 15 print(item