I know dictionary's are not meant to be used this way, so there is no built in function to help do this, but I need to delete every entry in my dictionary that has a specific value.
so if my dictionary looks like:
'NameofEntry1': '0'
'NameofEntry2': 'DNC'
...
I need to delete(probably pop) all the entries that have value DNC, there are multiple in the dictionary.
Modifying the original dict:
for k,v in your_dict.items():
if v == 'DNC':
del your_dict[k]
or create a new dict using dict comprehension:
your_dict = {k:v for k,v in your_dict.items() if v != 'DNC'}
From the docs on iteritems()
,iterkeys()
and itervalues()
:
Using
iteritems()
,iterkeys()
oritervalues()
while adding or deleting entries in the dictionary may raise aRuntimeError
or fail to iterate over all entries.
Same applies to the normal for key in dict:
loop.
In Python 3 this is applicable to dict.keys()
, dict.values()
and dict.items()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With