0

As i used dict in python, i want it output in my writen order ,

>>> print(json.dumps({'4': 5,'2':2, '6': 7,'0':0},sort_keys=False,indent=2, separators=(',', ': ')))
{
  "0": 0,
  "2": 2,
  "4": 5,
  "6": 7
}

but what i want it output as written, any methods?

Kewin
  • 248
  • 1
  • 4
  • 8
  • 2
    dicts have no order, they are **unordered**. You can use OrderedDict. – Daniel Apr 27 '15 at 07:34
  • Welcome to SO. If one of the answers below fixes your issue, you should accept it (click the check mark next to the appropriate answer). That does two things. It lets everyone know your issue has been resolved, and it gives the person that helps you credit for the assist. See [here](http://meta.stackexchange.com/a/5235/187716) for a full explanation. – fferri Jun 07 '15 at 08:28

2 Answers2

1

From the documentation of json.dumps:

If sort_keys is True (default: False), then the output of dictionaries will be sorted by key.

You specified sort_keys=False, however, a Python dictionary {...} is arbitrarily sorted, so when you pass it to the dumps function, you lose the order you just gave.

You can use an OrderedDict if you want to retain the order.

>>> json.dumps(OrderedDict([('4', 5), ('2', 2), ('6', 7), ('0', 0)]), indent=2, separators=(',', ': '))

{
  "4": 5,
  "2": 2,
  "6": 7,
  "0": 0
}
fferri
  • 18,285
  • 5
  • 46
  • 95
0

dicts have no order, they are unordered. You can use OrderedDict.

>>> print(json.dumps(OrderedDict([('4', 5), ('2', 2), ('6', 7), ('0', 0)]), indent=2, separators=(',', ': ')))

{
  "4": 5,
  "2": 2,
  "6": 7,
  "0": 0
}
Daniel
  • 42,087
  • 4
  • 55
  • 81