How to find common values in 2 dictionaries of the same key

I have two dictionaries:

dict1={1:["solomon", "Daniel", " taiwo", "David"], 2:["James", "Jason", " abbaly"], 3:["Sarah", "Abraham", "Johnson"]}

dict2={1:["ire", "kehinde", " taiwo", "David"], 2:["jah", "abbey", " abbaly"], 3:["sarai", "Abraham", "Johnson"]}

I want to find all common words in dict1[key] and dict2[same_key].

What is the best way to do that?


Solution 1:

Assuming dict1 and dict2 have the same keys, we can use a dictionary comprehension and the set intersection operator to do the following:

dict1={1:["solomon", "Daniel", " taiwo", "David"], 2:["James", "Jason", " abbaly"], 3:["Sarah", "Abraham", "Johnson"]}

dict2={1:["ire", "kehinde", " taiwo", "David"], 2:["jah", "abbey", " abbaly"], 3:["sarai", "Abraham", "Johnson"]}

print({key: list(set(dict1[key]) & set(dict2[key])) for key in dict1.keys()})

This comprehension can be further improved by doing the following (thanks Jon Clements!):

print({k: list(set(v).intersection(dict2[k])) for k, v in dict1.items()})