简体   繁体   中英

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

I've a dictionary with a (x,y) key, where (x,y) means the same as (y,x) , How should I do this ?

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 of doing this, so d.get((2,1)) would match the key (1,2) directly ? ideally i'd want to insert eg (2,1) and not have it be distinct from the (1,2) key as well.

Use frozensets rather than tuples.

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

You need your own datatype. Something that return the same value for __hash__ for (1, 2) and (2, 1) .

But why do you want to do this? Do you want a set rather than a tuple? That would look something like:

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'

Note that it must be a frozenset , because dict keys must be immutable.

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

Memory usage may be a consideration; how many of these do you have?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM