Everywhere I search, they say python dictionary's doesn't have any order. When I run code 1 each time shows a different output (random order). But when I run code 2 it always shows the same sorted output. Why is the dictionary ordered in the second snippet?
#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)
Outputs
code 1:
four 4
two 2
three 3
one 1
code 1 again:
three 3
one 1
two 2
four 4
code 2 (always):
1 10
2 20
3 30
4 40
Well, as of python 3.7, dictionaries remember the order of items inserted as well. Thus we are also able to sort dictionaries using python's built-in sorted() function. Just like with other iterables, we can sort dictionaries based on different criteria depending on the key argument of the sorted() function.
As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. This is considered an implementation detail in Python 3.6; you need to use OrderedDict if you want insertion ordering that's guaranteed across other implementations of Python (and other ordered behavior).
To sort a dictionary by value in Python you can use the sorted() function. Python's sorted() function can be used to sort dictionaries by key, which allows for a custom sorting method. sorted() takes three arguments: object, key, and reverse.
Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.
It's related to how hash randomisation is applied. Quoting docs (emphasis mine):
By default, the
__hash__()
values of str, bytes and datetime objects are “salted” with an unpredictable random value. Although they remain constant within an individual Python process, they are not predictable between repeated invocations of Python.
For each subsequent run, your strings (keys in snippet 1) are hashed with different salt value - therefore hash value is also changed. Hash values determine ordering.
For int
type, hash function never changes - in fact hash is always equal to integer value.
assert hash(42) == 42
If hashing function never changes, there is no change in ordering in subsequent runs.
For details in how Python dictionaries are implemented, you may refer to How are Python's Built In Dictionaries Implemented.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With