Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the values that are common to two dictionaries, even if the keys are different?

Starting from two different dictionaries:

dict_a = {'a': 1, 'b': 3, 'c': 4, 'd': 4, 'e': 6}
dict_b = {'d': 1, 'e': 6, 'a': 3, 'v': 7}

How can I get the common values even if they have different keys? Considering the above dictionaries, I would like to have this output:

common = [1, 3, 6]
like image 637
mgri Avatar asked Dec 14 '22 01:12

mgri


2 Answers

Create sets from the values:

list(set(dict_a.values()) & set(dict_b.values()))

This creates an intersection of the unique values in either dictionary:

>>> dict_a = {'a': 1, 'b': 3, 'c': 4, 'd': 4, 'e': 6}
>>> dict_b = {'d': 1, 'e': 6, 'a': 3, 'v': 7}
>>> list(set(dict_a.values()) & set(dict_b.values()))
[1, 3, 6]

Unfortunately, we can't use dictionary views here (which can act like sets), because dictionary values are not required to be unique. Had you asked for just the keys, or the key-value pairs, the set() calls would not have been necessary.

like image 108
Martijn Pieters Avatar answered Dec 16 '22 13:12

Martijn Pieters


Try this,

commom = [item for item in dict_b.values() if item in dict_a.values()]
like image 25
Rahul K P Avatar answered Dec 16 '22 15:12

Rahul K P