What is the most Pythonic way of doing the following:
Suppose I have 2 dictionaries A
and B
. Now the regular python equality for dictionaries will check that the value and key is the same in each dictionary, and if this holds for every element of the dictionary they are equal. I want to modify this to consider a dictionary equal if for all sets of keys having the same value in A
, each element in that set will have the same value in B
, but not necessarily the same one as in A
.
Example:
A = {'A':1, 'B':4, 'C':1}
B = {'A':9, 'B':2, 'C':9}
Here A == B
. Essentially this dictionary represents a set of sets, and I want to implement set equality over it.
My attempt
def eq(a,b):
if not a.keys() == b.keys():
return False
for grouping in ({k for k in a.keys() if a[k] == v} for v in a.values()):
if not len(set(b[x] for x in grouping)) == 1:
return False
return True
I don't really like this approach because it doesn't short circuit since the entire generator must be consumed to convert it to a set. The idea is to partition the first set into groups such that for every group every element in it will have the same value. Then I want to make sure that for each grouping the values of the elements of the grouping are the same in the other set.
Edit I'm sorry I couldn't explain it more clearly, I will give more examples. An easier way to think about it is this: I can convert any dictionary into a set of sets as follows:
A = {'A':3, 'B':3, 'C':3, 'R':4, 'T':4}
A = {{'A', 'B', 'C'}, {'R', 'T'}}
B = {'A':[], 'B':[], 'C':[], 'R':"", 'T':""}
B = {{'A', 'B', 'C'}, {'R', 'T'}}
A == B