English Grad
English Grad

Reputation: 1395

removing key value pairs by matching values python

I am searching for periods "." in a dictionary and trying to delete the key/value pair if I find it

if "." in dict.values():
    #delete key, value pair from the dictionary

I am sure this is very simple but I cannot seem to locate an explanation. Thanks for your help.

Upvotes: 2

Views: 2187

Answers (2)

Paul
Paul

Reputation: 43620

If you don't want to copy your dictionary, (for example if the dictionary is large, or you have a reference to it elsewhere) then you should do it this way:

ks = [k for k in d if d[k]=='.']
for k in ks:
    d.pop(k)

Create your list of keys to be removed ahead of time as shown above. You don't want to modify your dictionary while iterating over it.

Upvotes: 1

jabaldonedo
jabaldonedo

Reputation: 26572

Create a new dictionary without those unwanted values using dictionary comprehension. Here is an example of how to do it:

>>> old_dict = {'one': '.', 'two': 2, 'three':3, 'four':'.'}
>>> new_dict = {k:v for k,v in old_dict.iteritems() if not v == '.'}
>>> new_dict
 {'three': 3, 'two': 2}

using iteritems instead of items avoids creating an intermediate list and improves performance.

Upvotes: 7

Related Questions