1

I'm learning about OrderedDicts in python but when I create new dictionaries it preserves the order anyway. I can't seem to find a good example of why you'd ever need to use an OrderedDict.

For reference, if I do this:

x = {"one":1,"two":2,"three":3}

print(x)

it will always print out {'one': 1, 'two': 2, 'three': 3}

I'm just looking to understand why we need OrderedDicts.

Redcoatwright
  • 129
  • 1
  • 5
  • 17
  • 3
    What makes you think it will *always* do that? The order within a `dict` is **not** guaranteed. In fact, on my system that code prints `three`, then `one` then `two`. – Silvio Mayolo Nov 03 '17 at 20:01
  • 1
    What's your Python version? – Thomas Junk Nov 03 '17 at 20:04
  • 1
    I'm gonna guess you are on Python 3.6, where, as an implementation detail, `dict` objects maintain insertion order. However, this is still not *guaranteed*, thus, if you want to write maintainable code, you should use `OrderedDict`. Now, it is very likely that by the time 3.7 comes out, it *will* become guaranteed, in which case, `OrderedDict` will probably become a thin wrapper around `dict`, and will be kept around for backwards compatibility. – juanpa.arrivillaga Nov 03 '17 at 20:04

1 Answers1

3

I'm learning about OrderedDicts in python but when I create new dictionaries it preserves the order anyway.

This is accidentally the case with python 3.6 It is an implementation detail. See Dictionaries are ordered in Python 3.6+

Thomas Junk
  • 5,588
  • 2
  • 30
  • 43