Python dictionary from an object's fields
To easily create a dictionary from an object's fields, employ vars(obj) or obj.__dict__. These methods generate a dictionary mapping field names to associated values.
Example:
Result:
These tricks will exclude methods and class variables. They're designed for objects with a __dict__ attribute and may not work for all object types.
Dictionary behavior: dict inheritance
You can make an object behave like a dictionary by inheriting from dict. This is convenient when you want to directly use dictionary methods on the object.
Converting through Iteration: Implement __iter__
Implement the __iter__ method in your class to allow Iterable-to-Dict conversion with the built-in dict() function.
Avoiding Methods & Private Attributes
Sometimes you'll want to exclude methods and private attributes (those names prefixed with __). Use a dictionary comprehension to filter out these unwanted extras from your end result.
Introduction to object_to_dict Function
When converting objects to dictionaries is a frequent task, creating a dedicated function helps streamline the process:
Harmonizing with Class Decorators
When object-to-dictionary conversion becomes common in your code, the @dataclass decorator simplifies the process by including a built-in asdict() method.
Smarter with getattr: Covering all Grounds
When a class uses @property decorators or computed attributes, vars() and __dict__ won't capture those. But getattr() will!
Best of Both Worlds: Class & Instance Dictionaries
Why choose when you can combine class attributes and instance attributes in a single dictionary?!
Was this article helpful?