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