7

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.

coderkid
  • 648
  • 2
  • 8
  • 16

4 Answers4

23

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() or itervalues() while adding or deleting entries in the dictionary may raise a RuntimeError 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().

ChrisF
  • 134,786
  • 31
  • 255
  • 325
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
8

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'}
Jared
  • 25,627
  • 7
  • 56
  • 61
2

This should work:

for key, value in dic.items():
     if value == 'DNC':
         dic.pop(key)
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
Ankur Ankan
  • 2,953
  • 2
  • 23
  • 38
0

If restrictions re: modifying the dictionary while iterating on it is a problem, you could create a new class compatible with dict that stores a reverse index of all keys that have the given value (updated at create / update / delete of dict item), which can be arguments to del without iterating over the dict's items.

Subclass dict, and override __setitem__, __delitem__, pop, popitem and clear.

If this is an operation you're doing a lot of, that might be convenient and fast.

Chris Johnson
  • 20,650
  • 6
  • 81
  • 80