Python - Convert Dictionary to Dataclass
Convert Dictionary to Dataclass in Python
In this tutorial, you will learn how to convert a dictionary into a dataclass object in Python.
Dataclasses provide a convenient way to manage and manipulate structured data, and converting a dictionary to a dataclass object can help simplify data handling.
To convert a given dictionary to a dataclass,
- Create a dataclass definition from the keys of the given dictionary.
- Create an instance of this dataclass from the dictionary.
Examples
1. Converting a given Dictionary to Dataclass object
In this example, we'll convert a dictionary into a dataclass object using the make_dataclass
function from the dataclasses
module.
Python Program
from dataclasses import make_dataclass
# Define the dictionary
person_data = {
"name": "Surya",
"age": 25
}
# Convert dictionary to dataclass
Person = make_dataclass("Person", person_data.keys())
person = Person(**person_data)
print(person)
The make_dataclass
function dynamically creates a dataclass with fields corresponding to the keys in the dictionary.
Output
Person(name='Surya', age=25)
Summary
In this Python dataclasses tutorial, we learned how to convert a dictionary object into a dataclass object in Python using make_dataclass
function of the dataclasses module.