2

I have a dataset which might have n level of ordered dictionary of ordered dictionaries,Now i need to convert all of them into normal dictionaries,Is there a easier method to do other than recursive search and conversion.

from collections import OrderedDict
an=OrderedDict([('method', 'constant'), ('data', '1.225')])

aw=OrderedDict([('method', 'constant'), ('data', OrderedDict([('1.225','777')]))])

print dict(an)
print dict(aw)
{'data': '1.225', 'method': 'constant'}
{'data': OrderedDict([('1.225', '777')]), 'method': 'constant'}
jpp
  • 159,742
  • 34
  • 281
  • 339
Awin
  • 91
  • 1
  • 8

1 Answers1

2

Probably not. You can wrap your recursive algorithm in a function:

from collections import OrderedDict

def ordered_to_regular_dict(d):
    if isinstance(d, OrderedDict):
        d = {k: ordered_to_regular_dict(v) for k, v in d.items()}
    return d

aw = OrderedDict([('method', 'constant'), ('data', OrderedDict([('1.225','777')]))])
res = ordered_to_regular_dict(aw)

# {'data': {'1.225': '777'}, 'method': 'constant'}
jpp
  • 159,742
  • 34
  • 281
  • 339