sh kim sh kim - 4 months ago 44
Python Question

I want to keep order of OrderedDict with ujson

My function's return value type is

OrderedDict
,

and now I want to write this on the file:

Here's my code:

mainDict = OrderedDict([('a',1),('b',2),('c',3),('d',[4,5,6])])
with open(outFileName, 'w', encoding='utf-8') as outFile :
outFile.write(ujson.dumps(mainDict, indent=4))


I expected it to keep the order of the dictionary in the file, but it got mixed up.

Is it because of using
ujson.dumps
? and how can I keep the order of an
OrderedDict
in the output file?

Answer

Yes, it seems like ujson dumps the dictionary as an unordered dictionary by default, unlike the built-in json package. Set the sort_keys argument to true to dump the data as an ordered dictionary.

Here's my the sample code:

import ujson
import json
from collections import OrderedDict

mainDict = OrderedDict([('a',1),('b',2),('c',3),('d',[4,5,6])])

# Dump dictionary as it is without changing its state or order.
with open("ordereddict1.txt", 'w') as outFile :
    outFile.write(json.dumps(mainDict, indent=4))


# Without the sort_keys set to True, the dictionary will loose its
# order upon dump.
with open("unordereddict2.txt", 'w') as outFile :
  outFile.write(ujson.dumps(mainDict, indent=4))

# Maintain the ordering of dictionary upon dump.
with open("ordereddict2.txt", 'w') as outFile :
  outFile.write(ujson.dumps(mainDict, indent=4, sort_keys=True))
Comments