How to convert a nested OrderedDict to dict in python?

How to convert a nested OrderedDict to dict in python?

To convert a nested OrderedDict to a regular dictionary (dict) in Python, you can use a recursive function to handle the nested structure. Here's how you can achieve this:

from collections import OrderedDict def ordereddict_to_dict(ordered_dict): """Recursively convert an OrderedDict to a dict.""" return {k: ordereddict_to_dict(v) if isinstance(v, OrderedDict) else v for k, v in ordered_dict.items()} # Example usage ordered_dict = OrderedDict([ ("a", 1), ("b", OrderedDict([ ("c", 3), ("d", OrderedDict([("e", 5)])) ])) ]) regular_dict = ordereddict_to_dict(ordered_dict) print(regular_dict) 

This function checks if each value in the OrderedDict is an instance of OrderedDict. If it is, it calls itself recursively; otherwise, it keeps the value as it is. This ensures that all nested OrderedDict structures are converted to regular dictionaries.


More Tags

android-alarms ora-06512 msg facet-grid loops daterangepicker jquery-ui-autocomplete inline status persist

More Programming Guides

Other Guides

More Programming Examples