Python – Convert Dataclass to Dictionary

Convert Dataclass object to Dictionary in Python

In this tutorial, you will learn how to convert a dataclass instance object to a dictionary object in Python.

To convert a given dataclass object into a dictionary object, call dataclasses.asdict() function and pass the given dataclass object as argument. The function returns a dictionary representation of the given dataclass instance.

For example, if object is the dataclass instance, then the code snippet to convert this object into a dictionary is given below.

dataclasses.asdict(object)

Examples

1. Convert a simple dataclass instance to dictionary

In this example, we’ll create a dataclass to represent a Person with name and age attributes.

We shall create an instance of this dataclass person_1, and get the dictionary representation of this instance using dataclasses.asdict() method.

Python Program

import dataclasses
from dataclasses import dataclass

@dataclass
class Person:
    name: str
    age: int

# Create an instance of dataclass Person
person_1 = Person("Ram", 21)

# Convert dataclass to dictionary
person_1_dict = dataclasses.asdict(person_1)

print(f"Dictionary : \n{person_1_dict}")
Run Code Copy

Output

Dictionary : 
{'name': 'Ram', 'age': 21}

2. Convert nested dataclass instance to Dictionary

In this example, we’ll define two dataclasses: Person and Student. Student dataclass consists of the instance of Person dataclass as an attribute.

We shall create an instance of Student dataclass, student_1, and convert this instance into a dictionary object.

Python Program

import dataclasses
from dataclasses import dataclass

@dataclass
class Person:
    name: str
    age: int

@dataclass
class Student():
    student_id: str
    basic_details: Person

# Create an instance of dataclass Person
student_1 = Student("12345", Person("Ram", 21))

# Convert dataclass to dictionary
student_1_dict = dataclasses.asdict(student_1)

print(f"Dictionary :\n{student_1_dict}")
Run Code Copy

Output

Dictionary :
{'student_id': '12345', 'basic_details': {'name': 'Ram', 'age': 21}}

Summary

In this Python dataclasses tutorial, we learned how to convert a given dataclass instance into a dictionary object, with the help of example programs.

Related Tutorials

Code copied to clipboard successfully 👍