[Solved] Dictionary comprehension to compare two dictionaries [closed]


Create an intersection of the keys, then access the value in both dictionaries:

{k: dict1[k] * dict2[k] for k in dict1.viewkeys() & dict2}

This uses dictionary views which act as sets (and & creates a set intersection).

In Python 3 you get dicitonary views via the default methods:

{k: dict1[k] * dict2[k] for k in dict1.keys() & dict2}

By using the key set intersection, you ensure you only get keys that appear in both dictionaries.

solved Dictionary comprehension to compare two dictionaries [closed]