Look at a tuple in a python dictionary matching (x, y) or (y, x)

I have a dictionary with a key (x,y), where it (x,y)means the same as (y,x). How should I do it?

I can do:

>>> d = {(1,2): "foo"}
>>> i = d.get(2,1)
>>> if i is None:
...     i = d.get((1,2))
...
>>> i
'foo'

Is there a better way to do this, so d.get((2,1))would it directly correspond to the key (1,2)? Ideally, I would like to insert, for example. (2,1)and should not be different from the key (1,2).

+5
source share
3 answers

Use frozensets instead of tuples.

d = {frozenset((1,2)): "foo"}
print d.get(frozenset((2,1)))
+10
source

You need your own data type. Something returning the same value __hash__for (1, 2)and (2, 1).

? , ? :

d = {}
d[frozenset((1, 2))] = 'something'
s = frozenset((2,1))
if s in d:
    print '(2, 1) is in the dict'
else:
    print 'not found'

, frozenset, .

+1
def normalise_input_pair(x, y):
    return x, y if x <= y else y, x

It is possible to use memory; how many of them do you have?

>>> sys.getsizeof(frozenset((1,2)))
116
>>> sys.getsizeof((1,2))
36
>>>
+1
source

All Articles