Like the other answers correctly state, before Python 3.6, dictionaries are unordered.
That said, JSON is also supposed to have unordered mappings, so in principle it does not make much sense to store ordered dictionaries in JSON. Concretely, this means that upon reading a JSON object, the order of the returned keys can be arbitrary.
A good way of preserving the order of a mapping (like a Python OrderedDict) in JSON is therefore to output an array of (key, value) pairs that you convert back to an ordered mapping upon reading:
>>> from collections import OrderedDict
>>> import json
>>> d = OrderedDict([(1, 10), (2, 20)])
>>> print d[2]
20
>>> json_format = json.dumps(d.items())
>>> print json_format # Order maintained
[[1, 10], [2, 20]]
>>> OrderedDict(json.loads(json_format)) # Reading from JSON: works!
OrderedDict([(1, 10), (2, 20)])
>>> _[2] # This works!
20
(Note the way the ordered dictionary is constructed from a list of (key, value) pairs: OrderedDict({1: 10, 2: 20})
would not work: its keys are not necessarily ordered as in the dictionary literal, since the literal creates a Python dictionary whose keys are unordered.)
PS: Starting with Python 3.1, the json modules offers a hook for automatically converting a list of pairs (like above) to something else like an OrderedDict.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…