Reputation: 19
I have two python dictionaries:
dictA = {('a','b') : 1,('a','c') : 3,('b','c') : 1}
dictB = {('b','a') : 4,('a','d') : 6,('b','c') : 2}
I want to compare the keys of dictA and dictB for common keys. I have tried
comm = set(dictA.keys()) & set(dictB.keys())
But, this will only return ('b','c')
.
But,in my case, first key in both the dictionaries are same i.e. dictA[('a','b')]
is equivalent to dictB[('b','a')]
. How to do this ??
Upvotes: 0
Views: 159
Reputation: 91
Another solution, albeit less elegant than what Tony has suggested:
setA = [ frozenset(i) for i in dictA.keys() ]
setB = [ frozenset(i) for i in dictB.keys() ]
result = set(setA) & set(setB)
print( [tuple(i) for i in result] )
It uses frozenset in order to construct two sets of sets. Here's the kind of output you're gonna get:
[('b', 'c'), ('b', 'a')]
Upvotes: 1
Reputation: 2965
I have a more compact method.
I think it's more readable and easy to understand. You can refer as below:
These are your vars:
dictA = {('a','b') : 1,('a','c') : 3,('b','c') : 1}
dictB = {('b','a') : 4,('a','d') : 6,('b','c') : 2}
According your requirement to solve this problem:
print [ a for a in dictA if set(a) in [ set(i) for i in dictB.keys()]]
So you can get answer you want.
[('b', 'c'), ('a', 'b')]
Upvotes: 1
Reputation: 76712
That ('b','c')
is returned is the correct answer. The tuple ('a', 'b')
is not the same as the tuple ('b', 'a')
.
Upvotes: 0