如何从字典中删除项目

如何从字典中删除项目

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

问题描述

在迭代过程中从Python中删除项目是否合法?

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

例如:

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?

推荐答案

控制台中的一个简单测试显示,您可以在迭代过程中修改字典:

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

如delnan的回答中所述,删除条目会导致问题当迭代器尝试移动到下一个条目。相反,请使用 keys()方法获取密钥列表,并与之配合使用:

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}

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

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}

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

08-24 03:50