Why aren’t the values added to the dictionary in order?

Question

Why aren’t the values added to the dictionary in order?

Answer

In Python, a dictionary doesn’t add your items in the order you might expect. If we added 3 dishes, Burger, Salad, and Sammich, we’d expect them to appear in that order. But we’d be wrong!
There’s an advanced reason behind it, and like anything in programming, it’s because of efficiency. For now, just know that adding things to a dictionary does not add it in an order you’d expect, or necessarily at the end of the dictionary.

6 Likes

Could someone please answer the question? The current answer only states the obvious without giving any hints as to which algorithm is used

5 Likes

That’s the point. You should not rely on any order.
Python is free to do whatever it wants with that. (3.7 and later is not though, because it was added to the language specification that insertion order is kept)

6 Likes

You can order a dictionary with Python 3 as well: OrderedDict

from collections import OrderedDict
menu = OrderedDict()
menu[‘A’] = 15
menu[‘B’] = 14.5
menu[‘C’] = 10
print(menu)
# OrderedDict([(‘A’, 15), (‘B’, 14.5), (‘C’, 10)])

.

Documentation Python 3.7.2:
https://docs.python.org/3/library/collections.html?highlight=ordereddict#collections.OrderedDict

.

:skull_and_crossbones: Be careful:
You have to understand that dictionaries should not be used for ordering. You might lose performance.

  • List : We use a list if you have an ordered collection of items. These values can be CHANGED.

  • Dictionary : We use a dictionary when you have a set of UNIQUE keys that map to values to the keys
    A dictionary is an unordered collection of key-value pairs. The function of a dictionary is not to order the values but to make associations.

17 Likes

csssolver33151 , i have tried your code doing some modification, e.g.:
from collections import OrderedDict

menu = OrderedDict()

menu[‘D’] = 200

menu[‘A’] = 15

menu[‘B’] = 14.5

menu[‘C’] = 10

print(menu)

when you print it, it outputs in disorder

OrderedDict([(‘D’, 200),(‘A’, 15), (‘B’, 14.5), (‘C’, 10)])

The order for OrderedDict is based on insertion order. If you wanted to order it by something else you’d basically need to rebuild a new dictionary with that specific order.

1 Like