Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a dictionary key that has a certain value [duplicate]

Tags:

python

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.

like image 378
coderkid Avatar asked Jun 13 '13 19:06

coderkid


1 Answers

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().

like image 180
Ashwini Chaudhary Avatar answered Oct 15 '22 03:10

Ashwini Chaudhary