2

Note: this is not asking whether a Python dict keeps its order.

Question: is Python dict order guaranteed to where I can teach beginners that they can rely on it?

Sometimes my Python students assume that a dict will keep its order, because it does. But traditionally a dict is considered unordered.

Usually I teach them not to rely on this order, but I'm wondering whether it is a permanent part of Python and whether I can allow them to rely on it.

David B.
  • 727
  • 1
  • 5
  • 9

3 Answers3

2

Although python dict are now preserved in order, relying on that property is risky.

One of the side-effects is that it will cause your code to break down on old versions of CPython.

It is best to use OrderedDict instead.

For more information, you can see here: http://gandenberger.org/2018/03/10/ordered-dicts-vs-ordereddict/

Red
  • 26,798
  • 7
  • 36
  • 58
1

Formerly, in Python 3.6, this was an unofficial feature of the implementation of dict. As of 3.7, it is now an official (specced) feature of dict.

That officialness allows you to teach it this way about Python dict (but not about "dictionaries" (maps, hashes, etc) in general).

Practically speaking, the feature cannot be removed without significant backwards compatibility issues, and so won't be.

The remaining reasons to use OrderedDict involve a few additional capabilities like move_to_end(), and a few others, and dealing with the recentness of this spec: For example, if you want to run code in earlier versions of Python, or communicate orderedness to people or software libraries that are not aware of this new feature.

Joshua Fox
  • 18,704
  • 23
  • 87
  • 147
0

You should tell them that practically Python 3.7+ behaves like an OrderedDict (also Python 3.6 but this is not enforced), but that dictionaries don't necessary have this characteristic and is just how the implementation in Python works.

qedk
  • 468
  • 6
  • 18