Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dictionary from an object's fields

Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this:

>>> class Foo: ...     bar = 'hello' ...     baz = 'world' ... >>> f = Foo() >>> props(f) { 'bar' : 'hello', 'baz' : 'world' } 

NOTE: It should not include methods. Only fields.

like image 710
Julio César Avatar asked Sep 14 '08 18:09

Julio César


People also ask

How do I turn a object into a dictionary in Python?

By using the __dict__ attribute on an object of a class and attaining the dictionary. All objects in Python have an attribute __dict__, which is a dictionary object containing all attributes defined for that object itself. The mapping of attributes with its values is done to generate a dictionary.

Can you have a dictionary of objects Python?

Summary. The Python list stores a collection of objects in an ordered sequence. In contrast, the dictionary stores objects in an unordered collection. However, dictionaries allow a program to access any member of the collection using a key – which can be a human-readable string.

What is the __ dict __ attribute of an object in Python?

A special attribute of every module is __dict__. This is the dictionary containing the module's symbol table. A dictionary or other mapping object used to store an object's (writable) attributes.

Can a class contain a dictionary Python?

When it is required to form a dictionary with the help of an object and class, a class is defined. An 'init' function is defined, that assigns values to variables. An instance of the class is created, and the init function is called.


1 Answers

Note that best practice in Python 2.7 is to use new-style classes (not needed with Python 3), i.e.

class Foo(object):    ... 

Also, there's a difference between an 'object' and a 'class'. To build a dictionary from an arbitrary object, it's sufficient to use __dict__. Usually, you'll declare your methods at class level and your attributes at instance level, so __dict__ should be fine. For example:

>>> class A(object): ...   def __init__(self): ...     self.b = 1 ...     self.c = 2 ...   def do_nothing(self): ...     pass ... >>> a = A() >>> a.__dict__ {'c': 2, 'b': 1} 

A better approach (suggested by robert in comments) is the builtin vars function:

>>> vars(a) {'c': 2, 'b': 1} 

Alternatively, depending on what you want to do, it might be nice to inherit from dict. Then your class is already a dictionary, and if you want you can override getattr and/or setattr to call through and set the dict. For example:

class Foo(dict):     def __init__(self):         pass     def __getattr__(self, attr):         return self[attr]      # etc... 
like image 90
user6868 Avatar answered Oct 02 '22 23:10

user6868