如何在迭代时从字典中删除项目? [英] How to delete items from a dictionary while iterating over it?

查看:34
本文介绍了如何在迭代时从字典中删除项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中迭代字典时从字典中删除项目是否合法?

例如:

for k, v in mydict.iteritems():如果 k == val:del mydict[k]

这个想法是从字典中删除不满足特定条件的元素,而不是创建一个新字典,它是被迭代的一个子集.

这是一个好的解决方案吗?有没有更优雅/更有效的方法?

解决方案

对于 Python3(或更高版本):

<预><代码>>>>神话{'四':4,'三':3,'一':1}>>>对于列表中的 k(mydict.keys()):...如果 mydict[k] == 3:... del mydict[k]...>>>神话{'四':4,'一':1}

其余答案适用于 Python2,但不适用于 Python3 并引发 RuntimeError.

<块引用>

运行时错误:字典在迭代过程中改变了大小.

发生这种情况是因为 mydict.keys() 返回一个迭代器而不是一个列表.正如评论中所指出的,只需通过 list(mydict.keys())mydict.keys() 转换为列表,它应该可以工作.


对于python2:

控制台中的一个简单测试表明您不能在迭代字典时修改它:

<预><代码>>>>mydict = {'一':1,'二':2,'三':3,'四':4}>>>对于 k, v 在 mydict.iteritems() 中:...如果 k == '二':... del mydict[k]...------------------------------------------------------------回溯(最近一次调用最后一次):文件<ipython console>",第 1 行,在 <module> 中.运行时错误:字典在迭代期间改变了大小

如 delnan 的回答所述,当迭代器尝试移至下一个条目时,删除条目会导致问题.相反,使用 keys() 方法来获取密钥列表并使用它:

<预><代码>>>>对于 mydict.keys() 中的 k:...如果 k == '二':... del mydict[k]...>>>神话{'四':4,'三':3,'一':1}

如果需要根据items值进行删除,请改用items()方法:

<预><代码>>>>对于 k, v 在 mydict.items() 中:...如果 v == 3:... del mydict[k]...>>>神话{'四':4,'一':1}

Is it legitimate to delete items from a dictionary in Python while iterating over it?

For example:

for k, v in mydict.iteritems():
   if k == val:
     del mydict[k]

The idea is to remove elements that don't meet a certain condition from the dictionary, instead of creating a new dictionary that's a subset of the one being iterated over.

Is this a good solution? Are there more elegant/efficient ways?

解决方案

EDIT:

For Python3 (or greater):

>>> mydict
{'four': 4, 'three': 3, 'one': 1}

>>> for k in list(mydict.keys()):
...     if mydict[k] == 3:
...         del mydict[k]
...
>>> mydict
{'four': 4, 'one': 1}

The rest of the answers works fine with Python2 but do not work for Python3 and raises RuntimeError.

RuntimeError: dictionary changed size during iteration.

This happens because mydict.keys() returns an iterator not a list. As pointed out in comments simply convert mydict.keys() to a list by list(mydict.keys()) and it should work.


For python2:

A simple test in the console shows you cannot modify a dictionary while iterating over it:

>>> mydict = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
>>> for k, v in mydict.iteritems():
...    if k == 'two':
...        del mydict[k]
...
------------------------------------------------------------
Traceback (most recent call last):
  File "<ipython console>", line 1, in <module>
RuntimeError: dictionary changed size during iteration

As stated in delnan's answer, deleting entries causes problems when the iterator tries to move onto the next entry. Instead, use the keys() method to get a list of the keys and work with that:

>>> for k in mydict.keys():
...    if k == 'two':
...        del mydict[k]
...
>>> mydict
{'four': 4, 'three': 3, 'one': 1}

If you need to delete based on the items value, use the items() method instead:

>>> for k, v in mydict.items():
...     if v == 3:
...         del mydict[k]
...
>>> mydict
{'four': 4, 'one': 1}

这篇关于如何在迭代时从字典中删除项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆