Is there a clean way to have dict called on all attributes of a python object? Specifically, when I call dict on a my object, I get this:
{'edges': [<dawg.Edge instance at 0x107aa0200>,
<dawg.Edge instance at 0x10a581a70>,
<dawg.Edge instance at 0x10656a680>]}
but I'd like that output to be the instance's dict() instead of the instance description.
Edit: I guess I should clarify that I'm trying to JSONify the object, so I need type(obj['edges'][0]) to be a dict.
A dictionary value can be any type of object Python supports, including mutable types like lists and dictionaries, and user-defined objects, which you will learn about in upcoming tutorials.
__dict__ is A dictionary or other mapping object used to store an object's (writable) attributes. Or speaking in simple words every object in python has an attribute which is denoted by __dict__. And this object contains all attributes defined for the object.
Another method to convert a dictionary into a string in Python is using the dumps() method of the JSON library. The dumps() method takes up a JSON object as an input parameter and returns a JSON string. Remember! To call the dumps() method, you need to import the JSON library (at the beginning of your code).
We are calling a function here Dict2Class which takes our dictionary as an input and converts it to class. We then loop over our dictionary by using setattr() function to add each of the keys as attributes to the class. setattr() is used to assign the object attribute its value.
I think the repr solution would be cleaner, but you can also get what you want by adding this line after getting the dictionary you describe above (im calling it d1
)
d2 = {'edges' : map(lambda x: x.getDict(), d1['edges'])}
OR with list comprehension instead of map
d2 = {'edges' : [i.getDict() for i in d1['edges']]}
If you can describe for me what you want a little more I'll try to either implement getDict or write something more in that lambda, but I'm not sure enough about what you're going for. Is it the dictionary of all of edges fields?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With