Ok so I can use an OrderedDict in json.dump
. That is, an OrderedDict can be used as an input to JSON.
But can it be used as an output? If so how? In my
In addition to dumping the ordered list of keys alongside the dictionary, another low-tech solution, which has the advantage of being explicit, is to dump the (ordered) list of key-value pairs ordered_dict.items()
; loading is a simple OrderedDict(
. This handles an ordered dictionary despite the fact that JSON does not have this concept (JSON dictionaries have no order).)
It is indeed nice to take advantage of the fact that json
dumps the OrderedDict in the correct order. However, it is in general unnecessarily heavy and not necessarily meaningful to have to read all JSON dictionaries as an OrderedDict (through the object_pairs_hook
argument), so an explicit conversion of only the dictionaries that must be ordered makes sense too.