The easiest solution is to use JSON dumps and downloads.
from json import loads, dumps from collections import OrderedDict def to_dict(input_ordered_dict): return loads(dumps(input_ordered_dict))
NOTE. The above code will work for dictionaries that are known by json as serializable objects. A list of default object types can be found here.
So, this should be enough if the ordered dictionary does not contain special meanings.
EDIT: Based on the comments, let's improve the code above. Suppose input_ordered_dict may contain custom class objects that cannot be serialized by json by default. In this scenario, we should use the json.dumps default parameter with the json.dumps native serializer.
(eg):
from collections import OrderedDict as odict from json import loads, dumps class Name(object): def __init__(self, name): name = name.split(" ", 1) self.first_name = name[0] self.last_name = name[-1] a = odict() a["thiru"] = Name("Mr Thiru") a["wife"] = Name("Mrs Thiru") a["type"] = "test"
This example can be extended to a much larger area. We can even add filters or change the value of our need. Just add another part to the custom_serializer function
def custom_serializer(obj): if isinstance(obj, Name): return obj.__dict__ else: # Will get into this if the value is not serializable by default # and is not a Name class object return None
The function that is listed above, in the case of custom serializers, should be:
from json import loads, dumps from collections import OrderedDict def custom_serializer(obj): if isinstance(obj, Name): return obj.__dict__ else: # Will get into this if the value is not serializable by default # and is also not a Name class object return None def to_dict(input_ordered_dict): return loads(dumps(input_ordered_dict, default=custom_serializer))
thiruvenkadam Dec 09 '14 at 6:54 2014-12-09 06:54
source share