完美解决python遍历删除字典里值为空的元素报错问题

yipeiwu_com6年前Python基础

exam = { 'math': '95', 'eng': '96', 'chn': '90', 'phy': '', 'chem': '' }

使用下列遍历的方法删除:

1. for e in exam:
2. if exam[e] == '':
3. 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

正确做法:

1. s = {"1":a,"2":b,"3":c,"4":d,"5":e}
2. s_key = list(s.keys())
3. for k_s in s_key:

4.#比如我要删除第四个元素

5.del s["4"]

只是在for循环中,相当于对链表的操作,它会自动调用next方法!

字典的迭代器会遍历它的键,在这个过程中,不能改变这个字典!不能删除、添加数据

要先记录要删除的元素的索引,遍历完后再删除,exam.keys()返回的是一个独立的列表

以上这篇完美解决python遍历删除字典里值为空的元素报错问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

pytorch打印网络结构的实例

pytorch打印网络结构的实例

最简单的方法当然可以直接print(net),但是这样网络比较复杂的时候效果不太好,看着比较乱;以前使用caffe的时候有一个网站可以在线生成网络框图,tensorflow可以用tens...

Python的string模块中的Template类字符串模板用法

string.Template() string.Template()内添加替换的字符, 使用"$"符号, 或 在字符串内, 使用"${}"; 调用时使用string.substitut...

基于Python的关键字监控及告警

为了解决日志文件监控的问题, 使用python脚本完成了基于关键字的告警功能 环境 python 2.7 依赖包 time \ traceback \ filelock \ loggin...

Python version 2.7 required, which was not found in the registry

Python version 2.7 required, which was not found in the registry

安装PIL库的时候,直接提示:Python version 2.7 required, which was not found in the registry。 如图: 大意是说找不到...

python中执行shell的两种方法总结

一、使用python内置commands模块执行shell commands对Python的os.popen()进行了封装,使用SHELL命令字符串作为其参数,返回命令的结果数据以及命令...