Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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 e.g. (2,1) and not have it be distinct from the (1,2) key as well.

like image 886
Anonym Avatar asked Feb 04 '11 00:02

Anonym


2 Answers

Use frozensets rather than tuples.

d = {frozenset((1,2)): "foo"}
print d.get(frozenset((2,1)))
like image 146
btilly Avatar answered Oct 02 '22 20:10

btilly


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.

like image 28
Mikel Avatar answered Oct 02 '22 20:10

Mikel