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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With