print [(d1[key], d2[key]) for key in d1.viewkeys() & d2]
# [(2, 25), (3, 11)]
d1.viewkeys() & d2
is used to get the keys which are present in both the dictionaries. Once we get that, simply get the values corresponding to that from both the dictionaries.
This works because, as per the Dictionary View Objects Python 2.7 Documentation,
Keys views are set-like since their entries are unique and hashable.
Since viewkeys
are already set-like, we can use set operations on them directly.
Note: If you are using Python 3.x, then you have to use keys
function, like this
print([(d1[key], d2[key]) for key in d1.keys() & d2])
because, as per the Dictionary View Objects Python 3.x Documentation,
The objects returned by dict.keys(), dict.values() and dict.items() are view objects.
Since keys
itself returns a view object, and as their entries are unique and hashable, we can use that like set.
Note: In Python 2.x, dict.keys
returns a list of keys. Since we cannot do set operations on a list, we cannot use the Python 3.x solution.