Open In App

How to convert a nested OrderedDict to dict?

In this article, we will discuss how to convert a nested OrderedDict to dict? Before this we must go through some concepts:

To define the nested OrderedDict, we are using the collections module in python.






#import package
from collections import OrderedDict
 
# define OrderedDict
od1 = OrderedDict([('1', 'one'), ('2', 'two')])
print(type(od1))
print(od1)
 
# define nested OrderedDict
od2 = OrderedDict([('1', 'one'),
                   ('2', OrderedDict([('-2',
                                       '-ive'),
                                      ('+2',
                                       '+ive')]))])
print(type(od2))
print(od2)

Output:

<class ‘collections.OrderedDict’>



OrderedDict([(‘1’, ‘one’), (‘2’, ‘two’)])

<class ‘collections.OrderedDict’>

OrderedDict([(‘1’, ‘one’), (‘2’, OrderedDict([(‘-2’, ‘-ive’), (‘+2’, ‘+ive’)]))])

We can convert the OrderedDict to dict in just one line, but this is for only simple OrderedDict, not for the nested OrderedDict.




# import package
from collections import OrderedDict
 
# define OrderedDict
od1 = OrderedDict([('1', 'one'), ('2', 'two')])
 
# convert to dict
od1 = dict(od1)
 
# display dictionary
print(type(od1))
print(od1)

Output:

<class 'dict'>
{'1': 'one', '2': 'two'}

So, to convert nested OrderedDict to dict, we are using json.loads() and json.dumps() methods. 




# import package
from collections import OrderedDict
import json
 
# define nested OrderedDict
od2 = OrderedDict([('1', 'one'),
                   ('2', OrderedDict([('-2',
                                       '-ive'),
                                      ('+2',
                                       '+ive')]))])
# convert to dict
od2 = json.loads(json.dumps(od2))
 
# display dictionary
print(type(od2))
print(od2)

Output:

<class 'dict'>
{'1': 'one', '2': {'-2': '-ive', '+2': '+ive'}}

Article Tags :