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

Starting with 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 common values ​​even if they have different keys? Given the above dictionaries, I would like to get this conclusion:

common = [1, 3, 6]
+4
source share
3 answers

Creating sets of values:

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

This creates the intersection of unique values ​​in the 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 cannot use vocabulary representations here (which can act as sets) because the dictionary values ​​do not have to be unique. If you asked for only keys or key-value pairs, calls set()would not be necessary.

+6

,

commom = [item for item in dict_b.values() if item in dict_a.values()]
+4

& 2 , , dict.values. , Martijn Pieters:

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

2 :)

+2

Source: https://habr.com/ru/post/1666757/


All Articles