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....
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