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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20166749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:43:49  来源:igfitidea点击:

How to convert an OrderedDict into a regular dict in python3

pythontype-conversionordereddictionary

提问by Ben A.

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

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

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

采纳答案by ThiefMaster

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

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

回答by Kyle Neary

It is easy to convert your OrderedDictto a regular Dictlike this:

很容易将您的转换OrderedDict为这样的常规Dict

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:

如果您必须将其作为字符串存储在数据库中,则使用 JSON 是一种可行的方法。这也很简单,您甚至不必担心转换为常规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)

回答by thiruvenkadam

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

尽管这是一个老问题,但我想说,dict如果您在有序 dict 中有一个有序的 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

回答by spg

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

如果您正在寻找不使用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)

回答by Ramesh K

Its simple way

它的简单方法

>>import json 
>>from collection import OrderedDict

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

回答by radtek

Here is what seems simplest and works in python 3.7

这是在python 3.7中看起来最简单且有效的方法

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

回答by Micheal J. Roberts

I think a workaround for the nested OrderedDictproblem would be to utilise:

我认为嵌套OrderedDict问题的解决方法是使用:

import json
from collections import OrderedDict

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

The resulting data structure will be a pure dictand not a dictwith OrderedDictvalues.

生成的数据结构将是纯数据结构,dict而不是dict带有OrderedDict值的数据结构。

回答by Vitalii Dmitriev

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

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

from collections import OrderedDict

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