Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary order in python

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
like image 884
lordkian Avatar asked Dec 28 '15 19:12

lordkian


People also ask

Can we order dictionary in Python?

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.

Does order of dictionaries matter Python?

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).

How do you reorder a dictionary in Python?

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.

Can a dictionary be ordered?

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.


1 Answers

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.

like image 170
Łukasz Rogalski Avatar answered Sep 30 '22 17:09

Łukasz Rogalski