1

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?

John Gordon
  • 29,573
  • 7
  • 33
  • 58
  • what happend when dictionary1 and 2 has same values 2 times eg `dictp[1]=["solomon", "Daniel", " taiwo", "David", "David"]` and d`ict2=["ire", "kehinde", " taiwo", "David"]`, what should be output then ? – sahasrara62 Jan 23 '22 at 17:23
  • Does this answer your question? [Common elements comparison between 2 lists](https://stackoverflow.com/questions/2864842/common-elements-comparison-between-2-lists) – Tomerikoo Jan 24 '22 at 12:50

2 Answers2

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()})
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
0
for key in dict1:
    if key in dict2:
        print(word for word in dict1[key] if word in dict2[key])
John Gordon
  • 29,573
  • 7
  • 33
  • 58