views:

66

answers:

2

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?

+4  A: 

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
Whoops, sorry for my earlier (deleted) comment, I misunderstood the question. +1
Tamás
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
+1  A: 

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
yes seems to be - but good solution 1 line etration :)
Tumbleweed
I would suggest vk = set((v, k) for (k, v) in kv) to avoid an O(n^2) complexity
Xavier Combelle
yess it worked I used like this, result = [(k, v) for (k, v) in kv if (v, k) in kv and k!=v]
Tumbleweed
list comprehension is a loop.
SilentGhost