how.wtf

Convert OrderedDict to dict in Python

· Thomas Taylor

Upon first glance, converting an OrderedDict seems intuitive.

Convert OrderedDict to dict

1from collections import OrderedDict
2
3od1 = OrderedDict([("key1", "value1"), ("key2", "value2")])
4
5d1 = dict(od1)
6print(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:

 1from collections import OrderedDict
 2
 3od1 = OrderedDict(
 4    [
 5        ("key1", "value1"),
 6        ("key2", "value2"),
 7        ("key3", OrderedDict([("key3", "value3")])),
 8    ]
 9)
10
11d1 = dict(od1)
12print(d1)

Output:

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

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

 1from collections import OrderedDict
 2import json
 3
 4od1 = OrderedDict(
 5    [
 6        ("key1", "value1"),
 7        ("key2", "value2"),
 8        ("key3", OrderedDict([("key3", "value3")])),
 9    ]
10)
11
12d1 = json.loads(json.dumps(od1))
13print(d1)

Output:

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

#Python  

Reply to this post by email ↪