How to convert an OrderedDict into a regular dict in python3

后端 未结 8 626
天命终不由人
天命终不由人 2020-12-04 09:43

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

OrderedDict([(\'method\', \'constant\'), (\'data\', \'1.         


        
8条回答
  •  长情又很酷
    2020-12-04 09:56

    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)
    

提交回复
热议问题