Convert OrderedDict to dict in Python

Upon first glance, converting an OrderedDict seems intuitive.

Convert OrderedDict to dict

1
2
3
4
5
6
from collections import OrderedDict

od1 = OrderedDict([("key1", "value1"), ("key2", "value2")])

d1 = dict(od1)
print(d1)

Output:

1
{'key1': 'value1', 'key2': 'value2'}

Convert nested OrderedDicts to dict

However, if an OrderedDict has nested types of OrderedDicts, this method will not convert the nested OrderedDict types to dictionaries:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from collections import OrderedDict

od1 = OrderedDict(
    [
        ("key1", "value1"),
        ("key2", "value2"),
        ("key3", OrderedDict([("key3", "value3")])),
    ]
)

d1 = dict(od1)
print(d1)

Output:

1
{'key1': 'value1', 'key2': 'value2', 'key3': OrderedDict([('key3', 'value3')])}

Instead, a combination of json.loads() and json.dumps() can be used.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from collections import OrderedDict
import json

od1 = OrderedDict(
    [
        ("key1", "value1"),
        ("key2", "value2"),
        ("key3", OrderedDict([("key3", "value3")])),
    ]
)

d1 = json.loads(json.dumps(od1))
print(d1)

Output:

1
{'key1': 'value1', 'key2': 'value2', 'key3': {'key3': 'value3'}}