Search code examples
pythondictionarynested-loops

How can I prevent adding the same value (With another key) into a dictionary?


I need to fill a dictionary with pairs key-value given by the next code:

for i in range(1,n+1):
    d = {}
    Ri = Vector([#SomeCoordinates])

    for k in range(1,n+1):
        Rk = Vector([#SomeCoordinates])

        if i != k:
            d['R'+str(i)+str(k)] = (Rk-Ri).mod  # Distance between Ri and Rk
        else:
            None

""" Since  (Rk-Ri).mod  gives me the distance between two points (i and k),     
it's meaningless to calc the distance if i == k. """

Here's the problem:

'Rik' represents the same distance as 'Rki' and I don't want to add a distance twice.

Then, I tried with this code:

        if i != k and ( ('R'+str(i)+str(k)) and ('R'+str(k)+str(i)) ) not in d:
            d['R'+str(i)+str(k)] = (Rk-Ri).mod
        else:
            None

but the problem is still there.

When I "print d" I get R12 but also R21 (And the same with every pair of numbers " i k ").

What can I do?


Solution

  • You could use the following:

    d = {}
    for i in range(1, n + 1):
        Ri = Vector([#SomeCoordinates]).
        for k in range(i + 1, n + 1):
            Rk = Vector([#SomeCoordinates])
            d[i, k] = d[k, i] = (Rk - Ri).mod 
    

    This way we ensure we'll take only a pair (by enforcing k > i) and then we can assign to the dictionary the distance for both (i, k) and (k, i).

    I used d[i, k] instead of d['R' + str(i) + str(k)] because the latter has the following disadvantage: We can't infer for example, if d['R123'] refers to (12, 3) or (1, 23).

    Also, I moved dictionary initialisation (d = {}) outside both loops, because it's initialised for each i.