[英]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.
以下是我正在使用的更大词典的示例。我遇到的一个问题是键有时会出现在值中(即键``25-3''包含``25-3'',我想删除它。
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) 查看错误(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): 如果您想保留条目但只更改值,则可以使用(如Tomerikoo在评论中观察到的):
cat_map = {k:[x for x in v if x != k] for k,v in cat_map.items()}
Problem : 问题 :
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. del cat_map[cat_map[k].index(item)]
, cat_map[k].index(item)
将返回item的索引,该索引是cat_map
词典中不可用的整数。 Hence, the KeyError
. KeyError
。 Use list remove
, but only with a membership check prior to that. 使用列表
remove
,但只能在此之前进行成员资格检查。
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.