[python] How to convert an OrderedDict into a regular dict in python3

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

This question is related to python type-conversion ordereddictionary

The answer is


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)

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

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


A version that handles nested dictionaries and iterables but does not use the json module. Nested dictionaries become dict, nested iterables become list, everything else is returned unchanged (including dictionary keys and strings/bytes/bytearrays).

def recursive_to_dict(obj):
    try:
        if hasattr(obj, "split"):    # is string-like
            return obj
        elif hasattr(obj, "items"):  # is dict-like
            return {k: recursive_to_dict(v) for k, v in obj.items()}
        else:                        # is iterable
            return [recursive_to_dict(e) for e in obj]
    except TypeError:                # return everything else
        return obj

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}

Its simple way

>>import json 
>>from collection import OrderedDict

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

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)

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to type-conversion

How can I convert a char to int in Java? pandas dataframe convert column type to string or categorical How to convert an Object {} to an Array [] of key-value pairs in JavaScript convert string to number node.js Ruby: How to convert a string to boolean Convert bytes to int? Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe SQL Server: Error converting data type nvarchar to numeric How do I convert a Python 3 byte-string variable into a regular string? Leading zeros for Int in Swift

Examples related to ordereddictionary

How to convert an OrderedDict into a regular dict in python3 Rename a dictionary key Converting dict to OrderedDict Accessing items in an collections.OrderedDict by index Can I get JSON to load into an OrderedDict? Using a list as a data source for DataGridView