1

My list is like

l1 = [ {k1:v1} , {k2:v2}, {v1:k1} ]

Is there any better way to check if any dictionary in the list is having reverse pair?

sth
  • 222,467
  • 53
  • 283
  • 367
shahjapan
  • 13,637
  • 22
  • 74
  • 104

2 Answers2

3

I would suggest to transform the dictionaries in tuple and put the tuple in a set. And look in the set if the reverse tuple is in the set. That would have a complexity of O(n) instead of O(n^2).

Xavier Combelle
  • 10,968
  • 5
  • 28
  • 52
  • Whoops, sorry for my earlier (deleted) comment, I misunderstood the question. +1 – Tamás Jun 25 '10 at 08:40
  • 1
    If you just want to know whether a reverse pair exists or not, then you can test it with `len(d) != len(set([frozenset(i) for i in d.items()]))`. I think this is what Xavier is suggesting. – Michael Dunn Jun 25 '10 at 08:53
1

This code seems to work without loop:

k1 = 'k1'
k2 = 'k2'
v1 = 'v1'
v2 = 'v2'
l1 = [ {k1:v1} , {k2:v2}, {v1:k1} ]

kv = [e.items()[0] for e in l1]
print(kv)

vk = [(v, k) for (k, v) in kv]
print(vk)

result = [(k, v) for (k, v) in kv if (k, v) in vk]
print(result)
Michał Niklas
  • 53,067
  • 18
  • 70
  • 114