[英]how to compare two dictionaries with different keys but similar values and delete the duplicates
I am quite new to python and I am keen on learning.我对 python 很陌生,我热衷于学习。 I have two dictionaries that have different keys but similar values in it, as follows:
我有两个字典,它们具有不同的键但具有相似的值,如下所示:
dict_a = {'r1': ['c5', 'c6', 'c7', 'c8'], 'r2': ['c9', 'c10', 'c11'], 'r3': ['c12', 'c13', 'c14', 'c15']}
dict_b = {'f1': ['c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'c10', 'c11', 'c12', 'c13', 'c14', 'c15']}
Is it possible to compare both dictionaries and delete the duplicate values in it?是否可以比较两个字典并删除其中的重复值? I would like to obtain the following dictionaries at the end:
最后我想获得以下词典:
dict_a_new = {'r1': ['c5', 'c6', 'c7', 'c8'], 'r2': ['c9', 'c10', 'c11'], 'r3': ['c12', 'c13', 'c14', 'c15']}
dict_b_new = {'f1': ['c1', 'c2', 'c3', 'c4'}
I have tried the following syntax, but it doesn't work for me.我尝试了以下语法,但它对我不起作用。
dict_b_new = {k: dict_b[k] for k in set(dict_b) - set(dict_a)}
Any suggestions will be highly appreciated.任何建议将不胜感激。
You can create a set with all the items in dict_a
, and then create dict_b_new
with all the items in dict_b that are not in the set:您可以使用
dict_a
中的所有项目创建一个集合,然后使用 dict_b 中不在该集合中的所有项目创建dict_b_new
:
set_a = {item for lst in dict_a.values() for item in lst}
dict_b_new = {k: [item for item in lst if item not in set_a] for k, lst in dict_b.items()}
Demo: https://replit.com/@blhsing/PuzzledAgreeableProspect演示: https://replit.com/@blhsing/PuzzledAgreeableProspect
I suppose dict_a
has multiple keys, not only r1
, r2
, r3
, and dict_b
has a single key.我想
dict_a
有多个键,不仅r1
, r2
, r3
和dict_b
有一个键。
from itertools import chain
difference = set(*dict_b.values()) - set(chain(*dict_a.values()))
# {'c1', 'c2', 'c3', 'c4'}
dict_b_new = {k: difference for k in dict_b.keys()}
itertools.chain
concatenate iterables. itertools.chain
连接可迭代对象。
Ref: https://docs.python.org/3/library/itertools.html#itertools.chain参考: https://docs.python.org/3/library/itertools.html#itertools.chain
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.