Skip to content

Object to dictionary conversion in Python

Object to dictionary conversion is a serialization technique used in Python to transform class instances into native dictionaries. This process is essential for data storage and transmission, as it allows complex objects to be represented in formats like JSON^[400-devops__09-Scripting-Language__python__introduction__part-3.json__README.md].

The __dict__ attribute

Python objects store their writable attributes in an internal dictionary called __dict__. Accessing this attribute provides a direct mapping of attribute names to their values, effectively converting the object state into a standard Python dictionary^[400-devops__09-Scripting-Language__python__introduction__part-3.json__README.md].

For example, given a Customer class instance:

customer = Customer("h", "Marcel", "Dempers")
The conversion can be performed via:
customer_dict = customer.__dict__
# Result: {'customerID': 'h', 'firstName': 'Marcel', 'lastName': 'Dempers'}
^[400-devops__09-Scripting-Language__python__introduction__part-3.json__README.md]

Necessity for JSON Serialization

The standard Python json library cannot directly serialize objects that are not basic types (e.g., dicts, lists, strings). Attempting to run json.dumps() on a dictionary containing class instances results in a TypeError because the Customer object is not JSON serializable^[400-devops__09-Scripting-Language__python__introduction__part-3.json__README.md].

To enable JSON serialization, a dictionary of dictionaries must be constructed. This involves iterating through the collection of objects and replacing each class instance with its __dict__ representation^[400-devops__09-Scripting-Language__python__introduction__part-3.json__README.md].

Implementation Workflow

A common implementation involves the following steps:

  1. Iterate through the collection of objects^[400-devops__09-Scripting-Language__python__introduction__part-3.json__README.md].
  2. Extract the data from the target object using .__dict__^[400-devops__09-Scripting-Language__python__introduction__part-3.json__README.md].
  3. Populate a new dictionary using the object's ID (or key) as the field and the extracted dictionary as the value^[400-devops__09-Scripting-Language__python__introduction__part-3.json__README.md].

Example Code

# Start with an empty dictionary
customerDict = {}

# Populate the new dictionary using object.__dict__
for id in customers:
    customerDict[id] = customers[id].__dict__
^[400-devops__09-Scripting-Language__python__introduction__part-3.json__README.md]

Once the data is in this format, it can be passed to json.dumps() for storage or transmission^[400-devops__09-Scripting-Language__python__introduction__part-3.json__README.md].

Sources