3

How can I have tuples or some other datastructure with the property that with the same elements, regardless of order, index to the same value in a dictionary?

Say I have a tuple (A, B) as a key to a dictionary d. So d[(A, B)] = 1 and d[(B,A)]) = 1. It doesn't have to be a tuple.

mrQWERTY
  • 4,039
  • 13
  • 43
  • 91
  • 4
    Probably frozenset, but note that frozenset won't distinguish the number of occurrences, either, so `(A, A, B)` will be the same as `(A, B, B)`. – BrenBarn Jul 18 '16 at 18:33
  • 2
    Another option is to use sorted tuples as keys. – user1302130 Jul 18 '16 at 18:34
  • 3
    There's also `frozenset(collections.Counter(your_tuple).items())`, which works nicely for unorderable tuple elements. – user2357112 Jul 18 '16 at 18:37
  • 3
    Or a custom tuple subclass which defines `__hash__` as `hash(tuple(sorted(self)))`... – Daniel Roseman Jul 18 '16 at 18:38
  • ^Now could someone please combine all of that into an answer (I'd like to save all of this somewhere :)). – Bahrom Jul 18 '16 at 18:59
  • @DanielRoseman: That doesn't do the right thing with `==`, and if you define `__eq__` to be consistent with that `__hash__`, you break `==` comparisons against regular tuples. – user2357112 Jul 18 '16 at 19:14

0 Answers0