What is the best way to remove a dictionary item by value in python?

I like following a "hit list" approach where you iterate through the dictionary, then add the ones you want to delete to a list, then after iterating, delete the entries from that list like so:

hitList =[] for dictEntry: if test condition, hitList.append

for entry in hitList: delete dict[entry]

this is just some pseudocode but i've been successful with this in the past


You must create a copy to iterate over as changing the size of the dictionary inside of a loop causes a RunTimeError. Iterate over key, value pairs in your dictionary copy using items() and compare each value to the value you are looking for. If they match, delete the key from the dictionary.

    for key, value in dict(myDict).items():
        if value == 42:
            del mydict[key]

Adding answer for question in the comments below as it was too big for a comment. Here is a quick console session showing that mydict.copy() and dict(myDict) accomplish the same thing.

>>>import copy
>>>dict1 = {1:"egg", "Answer":42, 8:14, "foo":42}
>>>dict2 = dict(dict1)
>>>dict3 = dict1.copy()
>>>dict4 = dict1
>>>dict1[1] = "egg sandwich"
>>>dict1
{'Answer': 42, 1: 'egg sandwich', 'foo': 42, 8: 14}
>>>dict2
{'Answer': 42, 1: 'egg', 'foo': 42, 8: 14}
>>>dict3
{'Answer': 42, 1: 'egg', 'foo': 42, 8: 14}
>>>dict4
{'Answer': 42, 1: 'egg sandwich', 'foo': 42, 8: 14}
>>>dict2['foo'] = "I pity the"
dict1
>>>{'Answer': 42, 1: 'egg sandwich', 'foo': 42, 8: 14}
>>>dict2
{'Answer': 42, 1: 'egg', 'foo': 'I pity the', 8: 14}
>>>dict3
{'Answer': 42, 1: 'egg', 'foo': 42, 8: 14}
>>>dict4
{'Answer': 42, 1: 'egg sandwich', 'foo': 42, 8: 14}
>>>dict4[8] = "new"
>>>dict1
{'Answer': 42, 1: 'egg sandwich', 'foo': 42, 8: 'new'}
>>>dict2
{'Answer': 42, 1: 'egg', 'foo': 'I pity the', 8: 14}
>>>dict3
{'Answer': 42, 1: 'egg', 'foo': 42, 8: 14}
>>>dict4
{'Answer': 42, 1: 'egg sandwich', 'foo': 42, 8: 'new'}
`

You can use a simple dict comprehension:

myDict = {key:val for key, val in myDict.items() if val != 42}

As such:

>>> {key:val for key, val in myDict.items() if val != 42}
{8: 14, 1: 'egg'}