Skip to content Skip to sidebar Skip to footer

How To Remove A Value But Keep The Corresponding Key In A Dictionary?

Suppose I have a dictionary: D1 = {'A1' : [2, 3], 'B1': [3, 3], 'C1' : [4, 5]} and I wanted to remove the all 3s from D1 so that I would get: D1 = {'A1' : [2], 'B1': [], 'C1' : [4

Solution 1:

Here's a one-liner:

threeless = {k: [e for e in v if e != 3] for k, v in D1.iteritems()}

Solution 2:

All the answers I've read seem to me to create a new object : new dic in Eric's answer, new lists in other answers.

I think it's better to perform in place modification of each list, particularly if the number of items in the dictionary and/or the number of elements of the lists are big:

D1 = {'A1' : [2, 3], 'B1': [3, 3], 'C1' : [4, 5]}

for li in D1.itervalues():
    while3in li:
        li.remove(3)

Solution 3:

Something like this works, assuming 3 is always appears in the value, not in the key

>>>for v in D1.values():...if3in v:...        v.remove(3)...>>>D1
{'A1': [2], 'C1': [4, 5], 'B1': [3]}

EDIT: just realized can be multiple occurence, try this one

>>>D1 = {'A1' : [2, 3], 'B1': [3, 3], 'C1' : [4, 5]}>>>for k, v in D1.items():...    D1[k] = filter(lambda x: x!=3, v)...>>>D1
{'A1': [2], 'C1': [4, 5], 'B1': []}

Solution 4:

forlin D1.itervalues():
    l[:] = [item foritemin l if item != 3]

Note that this is a weird and inefficient way to structure your data, and this removal will take a while.

Solution 5:

Here's an approach that loops through the keys and calls filter on the lists:

>>>D1 = {'A1' : [2, 3], 'B1': [3, 3], 'C1' : [4, 5]}>>>for k in D1:...   D1[k] = filter(lambda v: v != 3, D1[k])...>>>D1
{'A1': [2], 'C1': [4, 5], 'B1': []}

Post a Comment for "How To Remove A Value But Keep The Corresponding Key In A Dictionary?"