Why do python dictionaries change order?

The order of the objects stored in the dictionaries in python3.5 varies in different executions of the interpreter, but it seems to remain unchanged for the same instance of the interpreter.

$ python3 <(printf 'print({"a": 1, "b": 2})\nprint({"a": 1, "b": 2})\nprint({"a": 1, "b": 2})\nprint({"a": 1, "b": 2})')
{'b': 2, 'a': 1}
{'b': 2, 'a': 1}
{'b': 2, 'a': 1}
{'b': 2, 'a': 1}
$ python3 <(printf 'print({"a": 1, "b": 2})\nprint({"a": 1, "b": 2})\nprint({"a": 1, "b": 2})\nprint({"a": 1, "b": 2})')
{'a': 1, 'b': 2}
{'a': 1, 'b': 2}
{'a': 1, 'b': 2}
{'a': 1, 'b': 2}

I always thought the order was based on a key hash. Why is the order different from different python versions?

+4
source share
2 answers

Dictionaries use a function hash, and the order is based on a key hash. All rights reserved.

But, as pointed out in this Q & A , starting with python 3.3, the hash seed is randomly selected at runtime (not to mention that it depends on the versions of python).

, Python 3.3 -, - ( Python, -). , - Python.

, , , .

( , python 3.6), , .

+2

. , "" .

, .keys()

-2

Source: https://habr.com/ru/post/1675431/


All Articles