简体   繁体   中英

How to remove elements from lists in dictionaries based on condition in python

i have a dictionary where the keys are strings and the values are lists of strings. Below is a sample from a much larger dictionary I am working with.A problem I'm running into is that the keys sometimes appear in the values (ie. key '25-3' contains '25-3' and I'd like to remove it.

cat_map = {'11-1': ['41-4', '43-1', '11-2', '43-6'],
 '11-2': ['41-4', '43-1', '11-2', '43-6'],
 '11-3': [],
 '11-9': [],
 '13-1': [],
 '13-2': [],
 '15-1': [],
 '15-2': [],
 '17-1': [],
 '17-2': [],
 '17-3': [],
 '19-1': [],
 '19-2': [],
 '19-3': [],
 '19-4': [],
 '21-1': [],
 '21-2': ['43-2', '33-9', '39-6', '39-9', '25-3', '39-3', '39-7'],
 '23-1': [],
 '23-2': [],
 '25-1': [],
 '25-2': [],
 '25-3': ['43-2', '37-1', '39-6', '25-3', '39-3'],

I'm puzzled why the below didn't work

for k,v in cat_map.items():
    for item in v:
        if k == item:
            del cat_map[cat_map[k].index(item)]
        else:
            continue

See the error (KeyError2)

KeyError                                  Traceback (most recent call last)
<ipython-input-83-f4c2c0fde28b> in <module>
      2     for item in v:
      3         if k== item:
----> 4             del cat_map[cat_map[k].index(item)]
      5         else:
      6             continue

KeyError: 2

You are not accessing the lists correctly. You would want to do:

del cat_map[k][cat_map[k].index(item)]

but you could simplify this check by:

for k,v in cat_map.items():
    if k in v:
        v.remove(k)

You could use a dictionary comprehension to build up the dictionary that you want to keep:

cat_map = {k:v for k,v in cat_map.items() if not k in v}

If you want to keep the entry but just change the values, you could use (as Tomerikoo observes in the comments):

cat_map = {k:[x for x in v if x != k] for k,v in cat_map.items()}

Problem :

  • Using del cat_map[cat_map[k].index(item)] , cat_map[k].index(item) will return index of item which is an integer not available in cat_map dictionary. Hence, the KeyError .

Use list remove , but only with a membership check prior to that.

Here's the code:

for k, v in cat_map.items():
    if k in v:
        v.remove(k)
keys = list(cat_map.keys())

for key, value in cat_map.items():
    for index, element in enumerate(value):
        if element in key:
            del cat_map[key][index]

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