python – check if two keys of a dictionary have equal values

Question:

hello, I have a dictionary {'A': ['B', 'C'], 'B': ['A', 'C'], 'C': ['A', 'B']}, I would like to know if there is some way to check if for example the key 'A' and the key 'C' have the same elements and what they are.

Thanks

Answer:

d1 = {'A': ['B', 'C'], 'B': ['A', 'C'], 'C': ['A', 'B'], 'D': ['B', 'C']}

To test full equality

d1['A']==d1['D']
True

d1['A']==d1['B']
False

Or specifically for your question, looking for elements of A that are in C .

equals = []

for e in d1['A']:
    if e in d1['C']:
        equals.append(e)

print (equals)
['B']

Or more pythonically on a single line with list comprehension

equals = [equal for equal in d1['A'] if equal in d1['C']]
print (equals)
['B']
Scroll to Top