1

If I have a python dictionary (or set, or some other kind of unordered container) and I call __str__ or __repr__ on it, which order of keys and/or values can I expect?

Of course, as the name "unordered container" states there is no particular order of contained elements. Yet, if the contained elements are printed in arbitrary order, is this arbitrary order at least persistent?

  1. Will the string representation of the container always be the same (given I do not change anything about the container or its elements)? Or will the nth call to __repr__ or __str__ at some point change the order of printed elements?

  2. What happens if I re-create the dictionary with the very same content (maybe on a different machine) will the order of printed elements still be the same as before?

EDIT: Why is this question marked as duplicate? I am not asking why the order is arbitrary. I ask whether string representations are persistent. Which might depend on more than just the underlying hash mechanism.

SmCaterpillar
  • 6,683
  • 7
  • 42
  • 70
  • 2
    Since Python 3.3, the order [isn't](http://stackoverflow.com/questions/14956313/dictionary-ordering-non-deterministic-in-python3) persistent accross invocations of the interpreter, but is within the same session. – Zero Piraeus Sep 04 '14 at 15:42
  • @jonrsharpe: that's a bad example, because `d.keys()` and `d.values()` list the items in the same order provided there have been no mutations in between the two calls. You *can* rely on those methods listing items in the same order for a dict that is not mutated. – Martijn Pieters Sep 04 '14 at 15:45
  • 1
    @jonrsharpe: the order being stable in that case [is explicitly documented](https://docs.python.org/2/library/stdtypes.html#dict.items). – Martijn Pieters Sep 04 '14 at 15:46
  • @MartijnPieters good point, thanks; that was a bad example. – jonrsharpe Sep 04 '14 at 15:48
  • 1
    The order depends on two things: 1. the hash seed used (this is randomized at startup in Python 3.3 and later to prevent a denial-of-service attack, but you can used a fixed one by setting an environment variable) and 2. the order of insertions and deletions. Within a single Python process, the order is stable so long as you have not inserted or deleted any items. It can in theory be made stable across machines by setting PYTHONHASHSEED to the same value on all machines and by always defining the dictionary exactly the same way. I'd want to test it thoroughly though. – kindall Sep 04 '14 at 16:03
  • Dictionary `__str__ = __repr__` (it's the same method, or rather Python uses `__repr__` because dict doesn't define `__str__`), and they use the exact same order as `keys()` and `values()` and `items()`, and these never mutate the dictionary. The rest of the answer *remains the same*. Any answer to this post can be constructed entirely from the other post. – Martijn Pieters Sep 04 '14 at 16:43

0 Answers0