在做对员工信息增删改查这个作业时,有一个需求是通过用户输入的id删除用户信息。我把用户信息从文件提取出来储存在了字典里,其中key是用户id,value是用户的其他信息。在循环字典的时候,当用户id和字典里的key相等时,会删除这条信息,当时删除时报错RuntimeError: dictionary changed size during iteration。

for key in staff_info:
if user_id == key:
print(key)
staff_info.pop(key)
id_exist = True

参考:https://www.python.org/dev/peps/pep-0234/#dictionary-iterators

在官网看到解释:

Dictionaries implement a tp_iter slot that returns an efficient iterator that iterates over the keys of the dictionary. During such an iteration, the dictionary should not be modified, except that setting the value for an existing key is allowed (deletions or additions are not, nor is the update() method). This means that we can write

for k in dict: ...

which is equivalent to, but much faster than

for k in dict.keys(): ...

as long as the restriction on modifications to the dictionary (either by the loop or by another thread) are not violated.

意思是多字典在被循环的时候不能被循环删除和更新,除了给一个已经存在的key设置value。还说道 for kin dict: ...和for k in dict.keys(): ...效果是一样的,但是前者速度更快。

那就来试验一下:

a = {'a': 1, 'b': 0, 'c': 1, 'd': 0}

for key in a:
print(key, a[key]) for key in a.keys():
print(key, a[key]) # 两个循环效果一样 print(a.keys()) # dict_keys(['a', 'b', 'c', 'd'])
print(a) # {'a': 1, 'b': 0, 'c': 1, 'd': 0}

除了a.keys是dict_keys类型,它们的效果是一样的。

那么解决方案就出来了,转换成列表形式就OK了。

for key in list(staff_info.keys()):
if user_id == key:
print(key)
staff_info.pop(key)
id_exist = True
有道词典

for k in dict: ...

详细X

k的dict类型:…

循环字典进行操作时出现:RuntimeError: dictionary changed size during iteration的解决方案的更多相关文章

  1. 迭代var()内置函数的时候出现RuntimeError: dictionary changed size during iteration的解决办法

    下午看了Mr Seven的教学视频,其中有一段讲全局变量的视频,迭代输出全局变量的时候报错了. 视频中的做法: for k,v in vars().items(): print(k) 打印结果 for ...

  2. python错误之RuntimeError: dictionary changed size during iteration

    pythonn报错信息: C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\python.exe C:/Users/Ad ...

  3. python 报错RuntimeError: dictionary changed size during iteration

    a = {':0} for b in list(a.keys()): if a[b] == 0: del a[b] print(a) 报错是因为在字典迭代期间改变字典大小 我们可以通过取出字典的键值, ...

  4. Python面试题目之(针对dict或者set数据类型)边遍历 边修改 报错dictionary changed size during iteration

    # result 是一个字典, 把里面属性值是None的属性删除 for key in result: if not result[key]: del result[key] continue 但是报 ...

  5. python : dictionary changed size during iteration

    1. 错误方式 #这里初始化一个dict >>> d = {'a':1, 'b':0, 'c':1, 'd':0} #本意是遍历dict,发现元素的值是0的话,就删掉 >> ...

  6. Python字典的操作与使用

    字典的描述 字典是一种key-value的数据类型,使用就像我们上学用的字典,通过拼音(key)来查对应字的详细内容(value). 字典的特性 1.字典是无序的(不像列表一样有下标,它通过key来获 ...

  7. Python—字典的操作

    字典的操作: #字典的本质其实是dict类的对象 >>> a = dict([(")]) >>> a {'} 一.增加 >>> stud ...

  8. python中字典的操作

    ----------字典操作------------ --查字典1. 字典名["元素名称"]2. 字典名.get("元素名称")-获取不存在得元素名称,.get ...

  9. Python学习杂记_6_字典常用操作

    字典操作 字典是由一对花括号括起来的一组“键值对”,每个键值对就是字典的一个元素,元素在字典中是无序的,常见操作如下: info = { 'name':'xiaoming', 'sex':'nan', ...

随机推荐

  1. NET Core应用中实现与第三方IoC/DI框架的整合?

    NET Core应用中实现与第三方IoC/DI框架的整合? 我们知道整个ASP.NET Core建立在以ServiceCollection/ServiceProvider为核心的DI框架上,它甚至提供 ...

  2. HDU 1024 A - Max Sum Plus Plus DP + 滚动数组

    http://acm.hdu.edu.cn/showproblem.php?pid=1024 刚开始的时候没看懂题目,以为一定要把那n个数字分成m对,然后求m对中和值最大的那对 但是不是,题目说的只是 ...

  3. Unity Log重新定向

    Unity Log重新定向 使用Unity的Log的时候有时候需要封装一下Debug.Log(message),可以屏蔽Log或者把log内容写到文本中.通过把文本内容传送到服务器中,查找bug出现的 ...

  4. Adobe CC Family (CC 2015) 大师版

    Adobe CC Family (CC 2015) 大师版 v5.6#2 ###请彻底卸载旧版后再安装本版! 更新 Adobe Digital Publishing CC 2016.1更新 Adobe ...

  5. vi命令使用

    在vi下如何显示行号? 按Esc切换到命令行模式,输入: :set nu 如果您想每次进入vi都标出行号,编辑~/.vimrc文件.也就是在用户的主目录下,编辑存档.vimrc文件.里边写一行: se ...

  6. zuul prefix

    经过测试,书上应该是写错了,如果要全部的路由加前缀,需要将zuul.stripPrefix=true进行设置 而不是书上所说的false

  7. cloud turbine

    turbine是聚合服务器发送事件流数据的一个工具,hystrix的监控中,只能监控单个节点,实际生产中都为集群,因此可以通过 turbine来监控集群下hystrix的metrics情况,通过eur ...

  8. Java实现的断点续传功能

    代码中已经加入了注释,需要的朋友可以直接参考代码中的注释.下面直接上功能实现的主要代码: import java.io.File; import java.io.FileNotFoundExcepti ...

  9. optparse 模块

    一.optparse是专门用来在命令行添加选项的一个模块.支持python2.3及以上版本,从2.7版本之后,python不再更新该模块,2.7之后的版本推荐使用argparse模块. 二.optpa ...

  10. Nginx FastCGI PHP

    We can see this comment in nginx.conf. # pass the PHP scripts to FastCGI server listening on 127.0.0 ...