Python中实现两个字典列表的差集运算问题求助
字典列表的元素差集计算
我有两个字典列表,需要从第一个列表中移除第二个列表里存在的对应元素,尝试了一些方法但没成功,具体需求如下:
输入数据
第一个列表(待处理列表)
[ { "app_name": [ { "date": "2023.01.04", "platform": "web" }, { "date": "2022.12.13", "platform": "web" } ] }, { "another_app_name": [ { "date": "2022.12.25", "platform": "windows" }, { "date": "2022.12.31", "platform": "ios" } ] } ]
第二个列表(需要移除的元素列表)
[ { "app_name": [ { "date": "2023.01.04", "platform": "web" } ] }, { "another_app_name": [ { "date": "2022.12.31", "platform": "ios" } ] } ]
期望结果
[ { "app_name": [ { "date": "2022.12.13", "platform": "web" } ] }, { "another_app_name": [ { "date": "2022.12.25", "platform": "windows" } ] } ]
我尝试过的代码
for f, b in zip(all_pcap, failed_pcap): res = {key: f[key] - b.get(key, 0) for key in f}
解决方案
你之前的代码用了-运算符,但这个运算符对列表和字典不适用,得换思路:把要移除的元素转成可哈希的结构(比如元组),然后过滤第一个列表里的元素。
以下是可行的代码:
def dict_to_tuple(d): # 将字典转成有序元组,方便做集合对比 return tuple(sorted(d.items())) result = [] # 遍历两个列表对应的字典项 for main_item, remove_item in zip(all_pcap, failed_pcap): # 遍历每个字典里的键值对(这里每个字典只有一个键,对应app名称) for app_name, main_entries in main_item.items(): # 获取要移除的条目,转成集合 remove_entries = set(dict_to_tuple(entry) for entry in remove_item.get(app_name, [])) # 过滤主列表里不在移除集合中的条目 filtered_entries = [entry for entry in main_entries if dict_to_tuple(entry) not in remove_entries] # 把过滤后的结果加入最终列表 result.append({app_name: filtered_entries}) print(result)
代码解释
dict_to_tuple函数:字典本身不可哈希,没法直接放进集合,所以把字典转成有序的键值对元组,保证相同内容的字典转成的元组完全一致。- 遍历对应元素:用
zip匹配两个列表中每个app对应的字典项。 - 生成移除集合:把第二个列表里要移除的元素转成元组后存入集合,实现快速查找。
- 过滤主列表元素:遍历第一个列表的每个条目,只保留不在移除集合里的内容。
- 组装结果:把过滤后的条目重新组成字典,加入结果列表。
内容的提问来源于stack exchange,提问作者s.e
相关产品推荐
相关产品推荐

