I'm working on a project where I often want to turn class instances into dictionaries to write them to MongoDB. I'd like some feedback on the following:
def getDict(self):
self.dict = dict()
for key in self.__dict__.keys():
if key not in self.NOT_INCLUDE: # class variable
try:
self.dict[key] = getattr(getattr(self, key), "getDict")()
except:
self.dict[key] = getattr(self, key)
return self.dict
This will turn any class with getDict
into a dictionary, including any instance properties that themselves have a getDict
method.
Also please let me know if there's an easy way to do this with the standard library that I missed.