Sherzod Safoev
Sherzod Safoev

Reputation: 13

What is meant by the fact that dictionaries in python don't retain order? What is exactly meant by order in this case?

I am learning python basics, and trying to understand the logic of programming fully. In the tutorial about dictionaries it says that they don't follow order, which I don't really get but feel like is an important part to understand.

Upvotes: 0

Views: 41

Answers (1)

chepner
chepner

Reputation: 531055

Consider two dict instances in Python 3.7:

>>> d1 = {'a': 1, 'b': 2}
>>> d2 = {'b': 2, 'a': 1}

A dict remembers the order in which the keys were inserted, but only uses that information for purpose of iterating over the keys. As long as the set of keys are identical, and each key maps to the same value, two dicts are considered equal, regardless of their iteration order.

>>> d1 == d2
True
>>> list(d1)
['a', 'b']
>>> list(d2)
['b', 'a']

An OrderedDict, though, treats the insertion order as an integral property of the value itself.

>>> from collections import OrderedDict
>>> od1 = OrderedDict(d1)
>>> od2 = OrderedDict(d2)
>>> list(od1)
['a', 'b']
>>> list(od2)
['b', 'a']
>>> od1 == od2
False

Upvotes: 2

Related Questions