简体   繁体   中英

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 3 s from D1 so that I would get:

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

这里是单线:

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

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)

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

iterate over the keys of the D1 take the lists and remove 3 s 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]}
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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM