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?
Be aware that you’re currently testing for object identity (
isonly returnsTrueif 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 asBut this may not do what you want:
So you probably want
!=instead ofis not.