Dictionary order in python

Wherever I search, they say that the python dictionary has no order. When I run code 1, a different output is displayed each time (random order). But when I run code 2, it always shows the same sorted output. Why is the dictionary ordered in the second fragment?

   #code 1

    d = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
    for a, b in d.items():
        print(a, b)
   #code 2 

    d = {1: 10, 2: 20, 3: 30, 4: 40}
    for a, b in d.items():
        print(a, b)

results

code 1:

four 4
two 2
three 3
one 1

Code 1:

three 3
one 1
two 2
four 4

code 2 (always):

1 10
2 20
3 30
4 40
+4
source share
1 answer

This is due to how hash randomization is applied. Quoting docs (my attention):

__hash__() str, datetime "" . Python, Python.

( 1) , . .

int - - .

assert hash(42) == 42

, .

, Python, Python .

+12

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


All Articles