0

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.

  • 1
    It means that `{'a':1, 'b':2, 'c':3}` and `{'a':1, 'c':3, 'b':2,}` are equivalent. And if you input one, you may get the other as output. – Jonathan Hall May 29 '19 at 12:56
  • 1
    this might be easier to explain with sets now, since dicts have started to follow insertion order since python 3.6 (as implementation detail) and 3.7 (officially) – Paritosh Singh May 29 '19 at 12:56
  • 4
    @ArkistarvhKltzuonstev Python 3.7. Retained order is an implementation detail of CPython 3.6, not something that is guaranteed by the language. – chepner May 29 '19 at 12:58
  • 1
    Related: [Are sets ordered like dicts in python3.6](https://stackoverflow.com/questions/45581901/are-sets-ordered-like-dicts-in-python3-6) – Paritosh Singh May 29 '19 at 13:00

1 Answers1

2

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
chepner
  • 497,756
  • 71
  • 530
  • 681