Dexter
Dexter

Reputation: 53

Python- compare dictionary values (list) and get key

I have a dictionary EllipseDict of length len(EllipseDict)=309, I need to compare the values and return tuple of keys which have an intersection. This is the code I have written, it takes about 52.43 seconds. Can anyone suggest any improvements to this code ?

checked = []
intersectingEllipses = []
for k1, v1 in EllipseDict.items():
    for k2, v2 in EllipseDict.items():
        if k1 == k2:
            continue
        else:
            if (k1, k2) and (k2, k1) not in checked:
                checked.append((k1, k2))
                common = set(v1).intersection(v2)
                if len(common) != 0:
                   intersectingEllipses.append((k1, k2))

Upvotes: 0

Views: 68

Answers (1)

steliosbl
steliosbl

Reputation: 8921

A compound if statement with an and is interpreted like so:

if [condition A] and [condition B]

Now take a look at your if statement:

if (k1, k2) and (k2, k1) not in checked

This is true when:

  • (k1, k2) is truthey (this is your [condition A]) AND
  • (k2, k1) is not in checked (this is your [condition B])

What you probably meant was to check that the two tuples ((k1, k2) and (k2, k1)) are not in checked. For that, you need to change your condition to:

if (k1, k2) not in checked and (k2, k1) not in checked

Now your conditions are

  • (k1, k2) is not in checked AND
  • (k2, k1) is not in checked

Upvotes: 1

Related Questions