当关键字不明时从字典中删除项目 [英] Remove an item from a dictionary when its key is unknown
问题描述
按值从字典中删除某项的最佳方法是什么,即当该项的键未知时?这是一种简单的方法:
What is the best way to remove an item from a dictionary by value, i.e. when the item's key is unknown? Here's a simple approach:
for key, item in some_dict.items():
if item is item_to_remove:
del some_dict[key]
还有更好的方法吗?迭代字典时从字典中进行变异(删除项目)有什么问题吗?
Are there better ways? Is there anything wrong with mutating (deleting items) from the dictionary while iterating it?
推荐答案
请注意,您当前正在测试对象标识(如果两个操作数均由内存中的同一对象表示,则is
仅返回True
.两个对象与==
相等的情况并非总是如此.如果您故意这样做,则可以将代码重写为
Be aware that you're currently testing for object identity (is
only returns True
if both operands are represented by the same object in memory - this is not always the case with two object that compare equal with ==
). If you are doing this on purpose, then you could rewrite your code as
some_dict = {key: value for key, value in some_dict.items()
if value is not value_to_remove}
但这可能无法满足您的要求:
But this may not do what you want:
>>> some_dict = {1: "Hello", 2: "Goodbye", 3: "You say yes", 4: "I say no"}
>>> value_to_remove = "You say yes"
>>> some_dict = {key: value for key, value in some_dict.items() if value is not value_to_remove}
>>> some_dict
{1: 'Hello', 2: 'Goodbye', 3: 'You say yes', 4: 'I say no'}
>>> some_dict = {key: value for key, value in some_dict.items() if value != value_to_remove}
>>> some_dict
{1: 'Hello', 2: 'Goodbye', 4: 'I say no'}
因此,您可能希望使用!=
而不是is not
.
So you probably want !=
instead of is not
.
这篇关于当关键字不明时从字典中删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!