如何在python3中将OrderedDict转换为常规dict

问题:如何在python3中将OrderedDict转换为常规dict

我正在努力解决以下问题:我想转换成OrderedDict这样:

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

变成这样的常规字典:

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

因为我必须将其作为字符串存储在数据库中。转换后,顺序不再重要,因此无论如何我都可以保留订购的功能。

感谢您提供任何提示或解决方案,

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


回答 0

>>> 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'}
>>>

但是,要将其存储在数据库中,最好将其转换为JSON或Pickle之类的格式。使用Pickle,您甚至可以保留订单!

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


回答 1

即使这是一个古老的问题,我想说的是,dict如果您在命令字典中有命令字典,则使用将无济于事。可以转换这些递归有序字典的最简单方法是

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

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

回答 2

可以很容易地将您转换成OrderedDict这样的常规Dict

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

如果必须将其作为字符串存储在数据库中,则可以使用JSON。这也很简单,您甚至不必担心转换为常规代码dict

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

或直接将数据转储到文件中:

with open('outFile.txt','w') as o:
    json.dump(d, o)

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)

回答 3

如果要查找不使用json模块的递归版本:

def ordereddict_to_dict(value):
    for k, v in value.items():
        if isinstance(v, dict):
            value[k] = ordereddict_to_dict(v)
    return dict(value)

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)

回答 4

这是看起来最简单的方法,可在python 3.7中使用

from collections import OrderedDict

d = OrderedDict([('method', 'constant'), ('data', '1.225')])
d2 = dict(d)  # Now a normal dict

现在检查一下:

>>> type(d2)
<class 'dict'>
>>> isinstance(d2, OrderedDict)
False
>>> isinstance(d2, dict)
True

注意:这也有效,并且给出相同的结果-

>>> {**d}
{'method': 'constant', 'data': '1.225'}
>>> {**d} == d2
True

以及-

>>> dict(d)
{'method': 'constant', 'data': '1.225'}
>>> dict(d) == {**d}
True

干杯

Here is what seems simplest and works in python 3.7

from collections import OrderedDict

d = OrderedDict([('method', 'constant'), ('data', '1.225')])
d2 = dict(d)  # Now a normal dict

Now to check this:

>>> type(d2)
<class 'dict'>
>>> isinstance(d2, OrderedDict)
False
>>> isinstance(d2, dict)
True

NOTE: This also works, and gives same result –

>>> {**d}
{'method': 'constant', 'data': '1.225'}
>>> {**d} == d2
True

As well as this –

>>> dict(d)
{'method': 'constant', 'data': '1.225'}
>>> dict(d) == {**d}
True

Cheers


回答 5

如果您以某种方式想要一个简单而又不同的解决方案,则可以使用以下{**dict}语法:

from collections import OrderedDict

ordered = OrderedDict([('method', 'constant'), ('data', '1.225')])
regular = {**ordered}

If somehow you want a simple, yet different solution, you can use the {**dict} syntax:

from collections import OrderedDict

ordered = OrderedDict([('method', 'constant'), ('data', '1.225')])
regular = {**ordered}

回答 6

简单的方法

>>import json 
>>from collection import OrderedDict

>>json.dumps(dict(OrderedDict([('method', 'constant'), ('data', '1.225')])))

Its simple way

>>import json 
>>from collection import OrderedDict

>>json.dumps(dict(OrderedDict([('method', 'constant'), ('data', '1.225')])))