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?
d = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
for a, b in d.items():
print(a, b)
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
source
share