How to convert the OrderedDict to the normal dict but keep the same order as the OrderedDict?

3.4k views Asked by At

When I use the dict() the order is changed! How to get the dict follow the order of OrderedDict()?

>>> from collections import OrderedDict
>>> OrderedDict([('method', 'constant'), ('data', '1.225')])
OrderedDict([('method', 'constant'), ('data', '1.225')])
>>> dict(OrderedDict([('method', 'constant'), ('data', '1.225')]))
{'data': '1.225', 'method': 'constant'}
>>>

What I would like to get is the same order as OrderedDict():

{'method': 'constant','data': '1.225'}

If cannot convert, how to parse the OrderedDict such as

for key, value in OrderedDict....
1

There are 1 answers

0
AChampion On BEST ANSWER

If you just want to print out dict in order without the OrderedDict wrapper you can use json:

>>> import json
>>> od = OrderedDict([('method', 'constant'), ('data', '1.225')])
>>> print(json.dumps(od))
{"method": "constant", "data": "1.225"}

You can iterate an OrderedDict identically to a dict:

>>> for k, v in od.items():
...    print(k, v)
method constant
data 1.225