Reputation: 11
Having a requirement to convert nested dict of dict to nested ordered dict
user_dict = {"a": {"b": {"c":
{'d': 'e',
'f': 'g',
'h': 'i'
}}}}
Expected output:
cfg_opts = OrderedDict([('a', OrderedDict([('b', OrderedDict([('c', OrderedDict([('d', 'e'), ('f','g'), ('h', 'i')]))]))]))])
Upvotes: 1
Views: 293
Reputation: 36828
I would use recursive function for this task as follows
import collections
user_dict = {'a': {'b': {'c': {'d': 'e', 'f': 'g', 'h': 'i'}}}}
def orderify(d):
if isinstance(d,dict):
return collections.OrderedDict({k:orderify(v) for k,v in d.items()})
else:
return d
ordered_user_dict = orderify(user_dict)
print(ordered_user_dict)
output
OrderedDict([('a', OrderedDict([('b', OrderedDict([('c', OrderedDict([('d', 'e'), ('f', 'g'), ('h', 'i')]))]))]))])
Upvotes: 2