Remove a dictionary key that has a certain value
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()
.
You just need to make sure that you aren't modifying the dictionary while you are iterating over it else you would get RuntimeError: dictionary changed size during iteration
.
So you need to iterate over a copy of the keys, values (for d
use d.items()
in 2.x or list(d.items())
in 3.x)
>>> d = {'NameofEntry1': '0', 'NameofEntry2': 'DNC'}
>>> for k,v in d.items():
... if v == 'DNC':
... del d[k]
...
>>> d
{'NameofEntry1': '0'}
This should work:
for key, value in dic.items():
if value == 'DNC':
dic.pop(key)