Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive __dict__ call on python object?

Tags:

python

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.

like image 800
victor Avatar asked Dec 19 '10 21:12

victor


People also ask

Can Python dict value be object?

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.

What is self __ dict __ Python?

__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.

Can we convert DICT to string in Python?

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).

How do you convert a dictionary to a class?

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.


1 Answers

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?

like image 172
jon_darkstar Avatar answered Oct 17 '22 12:10

jon_darkstar