Home > database >  how to compare two dictionaries with different keys but similar values and delete the duplicates
how to compare two dictionaries with different keys but similar values and delete the duplicates

Time:01-05

I am quite new to python and I am keen on learning. 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.

CodePudding user response:

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:

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

CodePudding user response:

I suppose dict_a has multiple keys, not only r1, r2, r3, and dict_b has a single key.

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.

Ref: https://docs.python.org/3/library/itertools.html#itertools.chain

  • Related