new_programmer
new_programmer

Reputation: 75

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, 5]}

Upvotes: 1

Views: 2390

Answers (6)

eyquem
eyquem

Reputation: 27585

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():
    while 3 in li:
        li.remove(3)

Upvotes: 3

rnbguy
rnbguy

Reputation: 1399

iterate over the keys of the D1 take the lists and remove 3s from them.

D1 = {'A1' : [2, 3], 'B1': [3, 3], 'C1' : [4, 5]}
def rem_d(D1,n):
    for d in D1:
        D1[d] = [i for i in D1[d] if i != n]

rem_d(D1,3)
D1
{'A1' : [2], 'B1': [], 'C1' : [4, 5]}

Upvotes: 1

jterrace
jterrace

Reputation: 67143

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': []}

Upvotes: 1

Eric
Eric

Reputation: 97661

Here's a one-liner:

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

Upvotes: 5

user2357112
user2357112

Reputation: 281843

for l in D1.itervalues():
    l[:] = [item for item in l if item != 3]

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

Upvotes: 1

marcadian
marcadian

Reputation: 2618

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

>>> for v in D1.values():
...     if 3 in 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': []}

Upvotes: 2

Related Questions