George V. Reilly

OrderedDict Initialization

An Or­dered­Dict is a Python dict which remembers insertion order. When iterating over an Or­dered­Dict, items are returned in that order. Ordinary dicts return their items in an un­spec­i­fied order.

Ironically, most of the ways of con­struct­ing an ini­tial­ized Or­dered­Dict end up breaking the ordering in Python 2.x and in Python 3.5 and below. Specif­i­cal­ly, using keyword arguments or passing a dict (mapping) will not retain the insertion order of the source code.

Python 2.7.13 (default, Dec 18 2016, 07:03:39)
>>> from collections import OrderedDict

>>> odict = OrderedDict()
>>> odict['one'] = 1
>>> odict['two'] = 2
>>> odict['three'] = 3
>>> odict['four'] = 4
>>> odict['five'] = 5
>>> odict.items()
[('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5)]

>>> OrderedDict(one=1, two=2, three=3, four=4, five=5).items()
[('four', 4), ('one', 1), ('five', 5), ('three', 3), ('two', 2)]

>>> OrderedDict(dict(one=1, two=2, three=3, four=4, five=5)).items()
[('four', 4), ('five', 5), ('three', 3), ('two', 2), ('one', 1)]

>>> OrderedDict({"one": 1, "two": 2, "three": 3, "four": 4,
                 "five": 5}).items()
[('four', 4), ('three', 3), ('five', 5), ('two', 2), ('one', 1)]

Only passing an iterable of key-value pairs will retain the order.

>>> OrderedDict([("one", 1), ("two", 2), ("three", 3),
                 ("four", 4), ("five", 5)]).items()
[('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5)]

Note that Or­dered­Dict is noticeably slower than dict in Python 2.7, so only use Or­dered­Dict when insertion order matters.

In Python 3.6, the order of kwargs is preserved, thanks to the new compact im­ple­men­ta­tion of dict. Or­dered­Dict is also im­ple­ment­ed in C and its per­for­mance is on par with that of dict.

Python 3.6 dicts are now ordered too, but if you care about portable code (earlier CPython or other Python im­ple­men­ta­tions such as Jython), use Or­dered­Dict rather than relying on this im­ple­men­ta­tion detail.

Python 3.6.0 (default, Dec 24 2016, 08:01:42)
>>> from collections import OrderedDict

>>> OrderedDict(one=1, two=2, three=3, four=4, five=5).items()
odict_items([('one', 1), ('two', 2), ('three', 3), ('four', 4), 

>>> OrderedDict(dict(one=1, two=2, three=3, four=4, five=5)).items()
odict_items([('one', 1), ('two', 2), ('three', 3), ('four', 4), 

>>> OrderedDict({"one": 1, "two": 2, "three": 3, "four": 4,
                 "five": 5}).items()
odict_items([('one', 1), ('two', 2), ('three', 3), ('four', 4), 

>>> OrderedDict([("one", 1), ("two", 2), ("three", 3),
                 ("four", 4), ("five", 5)]).items()
odict_items([('one', 1), ('two', 2), ('three', 3), ('four', 4), 
blog comments powered by Disqus
Review: Skinny Dip » « I Haz Shoes