2

In this question, it was suggested that calling repr on a dictionary would be a good way to store it in another dictionary. This would depend on repr being the same regardless of how the keys are ordered. Is this the case?

PS. the most elegant solution to the original problem was actually using frozenset

Community
  • 1
  • 1
Casebash
  • 114,675
  • 90
  • 247
  • 350

3 Answers3

7

No, the order that keys are added to a dictionary can affect the internal data structure. When two items have the same hash value and end up in the same bucket then the order they are added to the dictionary matters.

>>> (1).__hash__()
1
>>> (1 << 32).__hash__()
1
>>> repr({1: 'one', 1 << 32: 'not one'})
"{1: 'one', 4294967296L: 'not one'}"
>>> repr({1 << 32: 'not one', 1: 'one'})
"{4294967296L: 'not one', 1: 'one'}"
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • 1
    +1: Note that even keys with different hash values can come into the same bucket. This depends on dictionary implementation. – Denis Otkidach Oct 22 '09 at 05:32
2

That's not the case -- key ordering is arbitrary.

If you'd like to use a dictionary as a key, it should be converted into a fixed form (such as a sorted tuple). Of course, this won't work for dictionaries with non-hashable values.

John Millikin
  • 197,344
  • 39
  • 212
  • 226
0

If you want to store a dictionary in another dictionary, there is no need to do any transformations first. If you want to use a dictionary as the key to another dictionary, then you need to transform it, ideally into a sorted tuple of key/value tuples.

Michael Dillon
  • 31,973
  • 6
  • 70
  • 106