在做对员工信息增删改查这个作业时,有一个需求是通过用户输入的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. scrapy-redis 分布式哔哩哔哩网站用户爬虫

    scrapy里面,对每次请求的url都有一个指纹,这个指纹就是判断url是否被请求过的.默认是开启指纹即一个URL请求一次.如果我们使用分布式在多台机上面爬取数据,为了让爬虫的数据不重复,我们也需要一 ...

  2. 关闭mysql validate-password插件

    mysql5.7 的validate-password对密码策略有限制,比如长度大小写,太麻烦,我习惯开发环境下为root,所以在开发环境关闭这个插件的话只需在/etc/my.cnf中添加valida ...

  3. 零基础逆向工程14_C语言08_指针02_反汇编

    1.指针数组 5: char* keyword[] = {"if", "for", "while", "switch"} ...

  4. layout_weight属性

    layout_weight 某个控件text多行,第一行对齐,baselineAligned = "false" 可使控件对齐 weight 计算规则 剩余尺寸=父布局尺寸-子布局 ...

  5. 重写strcat函数,以实现strcat的功能

    char * strcatTest(char *dst,const char *src);Action(){ char a[]="come on"; char b[]=" ...

  6. dataset datatable datacolums datarow

    DataSet 表示数据在内存中的缓存. 属性 Tables  获取包含在 DataSet 中的表的集合. ds.Tables["sjxx"] DataTable 表示内存中数据的 ...

  7. jsp之数据提交与获取(传统方法)

    package com.java.model; public class Student { private String name; private int age; public String g ...

  8. 剑指offer58 二叉树的下一个结点

    自己写的 class Solution { public: TreeLinkNode* GetNext(TreeLinkNode* pNode) { if(pNode == NULL) return ...

  9. python_98_面向对象_学校

    class School(object):#以后都加object(基类) def __init__(self, name, addr): self.name = name self.addr = ad ...

  10. Unity调用Windows窗口句柄,选择文件和目录

    T:2019-6-25 10:06:59 C:Scatt Kang using System; using System.Collections; using System.Collections.G ...