0

I'm trying to make a dictionary of pairs of values, but I don't want it added if the pair is already there (even reversed). So let's say (0,1) is already there, I don't want (1,0). This is my code but I'm looking for a more pythonic way of doing it, I'm sure there is one. PS. I can't use itertools for this exercise

    test = {(0,1):1, (0,2):2}
    for a in range(3):
        for b in range(3):
            if a!= b:
                if (b,a) not in test:
                    test[a,b]=4
user12195705
  • 147
  • 2
  • 10

2 Answers2

1

If you want a way to be sure that (a,b) and (b,a) never both get into the dictionary, you can loop like this:

test = {(0,1):1, (0,2):2}
for a in range(3):
    for b in range(a+1, 3):
        if (b,a) not in test.keys(): #pretty sure it's better to ask for .keys()
            test[a,b]=4

If you want to treat your keys as the appropriate data type, then don't use a tuple. Your business problem indicates that order doesn't matter. Tuples are ordered. So use something that isn't.

test = {set((0,1)):1, set((0,2)):2}
for a in range(3):
    for b in range(3):
        if a!= b:
            if set((b,a)) not in test.keys():
                test[set(a,b)]=4
Neil
  • 3,020
  • 4
  • 25
  • 48
-1

I'm not sure why this isn't Pythonic.

I would, however, make sure that (a,b) is in the dict only if a<=b, which means you don't have to check both pairs every time - just one of them.

zmbq
  • 38,013
  • 14
  • 101
  • 171