How do I get the attribute names and values of an object? I’m attempting to cast it to a dictionary so that I can easily JSON serialize the object.
Code:
class User:
...
def to_dict( self ):
dict = {}
for key, value in filter( lambda aname: not aname.startswith('_'), dir(self) ):
dict[key] = value
return dict
Error:
too many values to unpack
Use:
user = User({
's_email': 'bob@email.com',
's_password': 'password',
})
user.to_dict()
# JSON Serialize
Use
self.__dict__. It is a dictionary representing the namespace of the object.Note that given your code snippet, the dict returned by
.to_dict()would contain the key'to_dict'as the function does not start with an underscore. Probably a simple mistake in your post.If the list of attributes that you want to include in the returned dict is small (and doesn’t change much), I suggest being explicit about it and listing them