打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
python遍历删除字典里值为空的元素报错

python遍历删除字典里值为空的元素报错

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

Sheldon742

2013年01月10日提问

5 个回答

3赞
采纳
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).
2013年01月10日更新

leunggamciu1.1k

2013年01月10日回答
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
小顾de杂记 ? 一段关于Python字典遍历的“争论”
python数组的使用
Python 字典 dictionary changed size during iteration
Python中列表、字典、元组、集合数据结构整理
Python 列表 list 数组 array 常用操作集锦
Redis入门(1) - 使用Cli
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服