python删除dict空值元素报错RuntimeError原因,dictruntimeerror,exam = { mat
python删除dict空值元素报错RuntimeError原因,dictruntimeerror,exam = { mat
exam = { 'math': '95', 'eng': '96', 'chn': '90', 'phy': '', 'chem': '' }
使用下列遍历的方法删除:
for e in exam: if exam[e] == '': del exam[e]
结果出现下列错误,怎么解决:
Traceback (most recent call last): File "Untitled.py", line 3, in <module> for e in exam:RuntimeError: dictionary changed size during iteration
for k, v in exam.items(): if not v: exam.pop(k)
在使用迭代器遍历的过程中不能删除、添加数据
先记录要删除的元素的索引,遍历完后再删除
dict(filter(lambda x: x[1] != '', exam.items()))
for e in exam.keys(): if exam[e] == '': del exam[e]
for e in exam:
使用的是迭代器,它等于:
>>> exam = { 'math': '95', 'eng': '96', 'chn': '90', 'phy': '', 'chem': '' }>>> fetch = iter(exam)>>> while True:... try:... key = fetch.next()... except StopIteration:... break... if exam[key] == '':... del exam[key]...
只是在for循环中,它会自动调用next方法!
字典的迭代器会遍历它的键,在这个过程中,不能改变这个字典!exam.keys()返回的是一个独立的列表。
下面是来自PEP234的snapshot:
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).
编橙之家文章,
相关内容
- 是python的scrapy框架,xpath中可否以插入正则表达式,scr
- 求Python服务器后台间隔自动运行时间设置方法思路,
- django满足条件再输出的列表显示怎么写?,django怎么写
- 列表合并之后原相同数据不被覆盖应该写python源码,
- python新手问httplib和urllib2有哪些不同,httpliburllib2,想从
- python找到最近的字符要如何用正则匹配,python字符匹配
- 大家一起来讨论抽用正则取优酷视频并生成播放器的问
- tornado连接数据库报NameError是编码不对吗,tornadonameerr
- python编辑器vim补全插件vimrc与yum_extra_conf.py文件调试方法
- Python分割字符串如实现最优雅,python分割字符串, 分割
评论关闭