How to convert an OrderedDict into a regular dict

2019-01-13 12:20发布

I am struggling with the following problem: I want to convert an OrderedDict like this:

OrderedDict([('method', 'constant'), ('data', '1.225')])

into a regular dict like this:

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

because I have to store it as string in a database. After the conversion the order is not important anymore, so I can spare the ordered feature anyway.

Thanks for any hint or solutions,

Ben

6条回答
别忘想泡老子
2楼-- · 2019-01-13 12:22

If you are looking for a recursive version without using the json module:

def ordereddict_to_dict(value):
    for k, v in value.items():
        if isinstance(v, dict):
            value[k] = ordereddict_to_dict(v)
    return dict(value)
查看更多
对你真心纯属浪费
3楼-- · 2019-01-13 12:25

Here is what seems simplest and works in python 3.7

d = OrderedDict([('method', 'constant'), ('data', '1.225')])
d2 = dict(d)  # Now a normal dict
查看更多
Bombasti
4楼-- · 2019-01-13 12:29
>>> 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'}
>>>

However, to store it in a database it'd be much better to convert it to a format such as JSON or Pickle. With Pickle you even preserve the order!

查看更多
冷血范
5楼-- · 2019-01-13 12:30

Even though this is a year old question, I would like to say that using dict will not help if you have an ordered dict within the ordered dict. The simplest way that could convert those recursive ordered dict will be

import json
from collections import OrderedDict
input_dict = OrderedDict([('method', 'constant'), ('recursive', OrderedDict([('m', 'c')]))])
output_dict = json.loads(json.dumps(input_dict))
print output_dict
查看更多
时光不老,我们不散
6楼-- · 2019-01-13 12:31

It is easy to convert your OrderedDict to a regular Dict like this:

dict(OrderedDict([('method', 'constant'), ('data', '1.225')]))

If you have to store it as a string in your database, using JSON is the way to go. That is also quite simple, and you don't even have to worry about converting to a regular dict:

import json
d = OrderedDict([('method', 'constant'), ('data', '1.225')])
dString = json.dumps(d)

Or dump the data directly to a file:

with open('outFile.txt','w') as o:
    json.dump(d, o)
查看更多
倾城 Initia
7楼-- · 2019-01-13 12:39

Its simple way

>>import json 
>>from collection import OrderedDict

>>json.dumps(dict(OrderedDict([('method', 'constant'), ('data', '1.225')])))
查看更多
登录 后发表回答