0

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 ??

thefourtheye
  • 233,700
  • 52
  • 457
  • 497

3 Answers3

1

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')]
Burger King
  • 2,945
  • 3
  • 20
  • 45
1

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')]
Community
  • 1
  • 1
Alex Boklin
  • 91
  • 2
  • 6
0

That ('b','c') is returned is the correct answer. The tuple ('a', 'b') is not the same as the tuple ('b', 'a').

Anthon
  • 69,918
  • 32
  • 186
  • 246