繁体   English   中英

如果在至少一个列表中不存在键值对,则从两个字典列表之一中查找并删除该字典

[英]Find and remove the dict from one of two lists of dicts if there is a key-value pair not present in at least one of the lists

经过某些操作后,我得到了两个字典列表,这些字典按numeric_id键排序。 假设我有

list1 = [
        {'ref': 'link1', 'numeric_id': 1},
        {'ref': 'link2', 'numeric_id': 2},
        {'ref': 'link3', 'numeric_id': 3},
        {'ref': 'link4', 'numeric_id': 4},
        {'ref': 'link5', 'numeric_id': 5}
]

list2 = [
        {'ref': 'different_link1', 'numeric_id': 1},
        {'ref': 'different_link2', 'numeric_id': 2},
        {'ref': 'different_link4', 'numeric_id': 4},
        {'ref': 'different_link5', 'numeric_id': 5}
]

并且在第二个列表中,“ numeric_id”键中的值3不存在,而第一个列表中包含此类键值对。 然后,我必须从列表1中删除该词典,因为我只需要在两个列表中都具有基于numeric_id的匹配对。 当第一个列表中不存在该值而第二个列表中存在该值时,情况也可能相反。 我不知道会是什么情况。

结果应该是两个没有任何未配对元素的列表。 由于列表包含具有不同链接的字典,因此它们之间的唯一连接是numeric_id键的值

任务似乎很容易,但是我已经很迷路了。 能否请你帮忙? 找到了很多类似的问题,但找不到适合我的情况的正确解决方案。

提前致谢!

您可以使用filter

list1 = [{'numeric_id': 1, 'ref': 'link1'}, {'numeric_id': 2, 'ref': 'link2'}, {'numeric_id': 3, 'ref': 'link3'}, {'numeric_id': 4, 'ref': 'link4'}, {'numeric_id': 5, 'ref': 'link5'}]
list2 = [{'numeric_id': 1, 'ref': 'link1'}, {'numeric_id': 2, 'ref': 'link2'}, {'numeric_id': 4, 'ref': 'link4'}, {'numeric_id': 5, 'ref': 'link5'}]
new_list1 = list(filter(lambda x:any(c['numeric_id'] == x['numeric_id'] for c in list2), list1))
new_list2 = list(filter(lambda x:any(c['numeric_id'] == x['numeric_id'] for c in list1), list2))

输出:

[{'numeric_id': 1, 'ref': 'link1'}, {'numeric_id': 2, 'ref': 'link2'}, {'numeric_id': 4, 'ref': 'link4'}, {'numeric_id': 5, 'ref': 'link5'}]
[{'numeric_id': 1, 'ref': 'link1'}, {'numeric_id': 2, 'ref': 'link2'}, {'numeric_id': 4, 'ref': 'link4'}, {'numeric_id': 5, 'ref': 'link5'}]

也许你可以试试这个:
1.从list2提取numeric_id
2.如果list1numeric_idlist2则追加list1每个元素

list2_numeric_id = [element["numeric_id"] for element in list2]
[element for element in list1 if element["numeric_id"] in list2_numeric_id]
>> [{'numeric_id': 1, 'ref': 'link1'}, {'numeric_id': 2, 'ref': 'link2'}, {'numeric_id': 4, 'ref': 'link4'}, {'numeric_id': 5, 'ref': 'link5'}]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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