Python – Convert instance to a dictionary

I’ve been using the salesforce-python-library which is awesome. The results returned are of type . I’ve been using getattr(inst, key, default_value) to get the value of the key but I found this cool way of converting an instance to a dictionary. If you try inst.__dict__, you may get errors if the class has native methods starting with __. Here’s a better solution:

inst_result = call_api()
dict_result = dict((name, getattr(inst_result, name)) for name in dir(inst_result) if not name.startswith('__'))

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s