← Python lessons

Python Dataclass asdict Examples

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

Python's asdict() turns a dataclass object into an ordinary dictionary, with one key per field. Dataclasses nested inside it become dictionaries too.

Read Python Dataclasses and Python OOP Composition with Dataclasses first. One example also uses json.dumps() from Python JSON. This lesson exports one record, shows why exported data is easier to pass on, exports records nested inside a record and compares asdict() with vars(). asdict() comes from Python's standard dataclasses module.

Convert one record

Import asdict from dataclasses beside dataclass. Pass it the object; it returns a new dictionary.

from dataclasses import asdict, dataclass@dataclassclass Book:    title: str    pages: intbook = Book("Dune", 412)data = asdict(book)print(data)print(data["pages"])

This prints {'title': 'Dune', 'pages': 412}, then 412. Each field name becomes a string key, in the order the class lists its fields. The values stay as they were. You now read a value by its key, data["pages"], not by data.pages.

Why export plain data

Code outside your program does not know your classes. The json module, a file or a web API all expect plain values: dictionaries, lists, strings and numbers. json.dumps() turns such values into one string of JSON text, ready to save or send.

import jsonfrom dataclasses import asdict, dataclass@dataclassclass Book:    title: str    pages: intbook = Book("Dune", 412)print(json.dumps(asdict(book)))print(json.dumps(book))  # this line raises TypeError

This prints {"title": "Dune", "pages": 412}, then stops with TypeError: Object of type Book is not JSON serializable. Keep the dataclass while your program works with the data, because its methods and field names help. Export with asdict() at the edge, when the data leaves your program.

Export nested records

asdict() goes into every field. A dataclass held in a field becomes a dictionary as well.

from dataclasses import asdict, dataclass@dataclassclass Battery:    capacity: int    used: int@dataclassclass Phone:    model: str    battery: Batteryphone = Phone("Pixel", Battery(3000, 500))data = asdict(phone)print(data)print(data["battery"]["used"])

This prints {'model': 'Pixel', 'battery': {'capacity': 3000, 'used': 500}}, then 500. data["battery"] is a dictionary, not a Battery, so a second key reads a value inside it. Dataclasses inside a list are converted the same way, as the next example shows.

asdict() or vars()

vars() also gives a dictionary of an object's fields, so the two are easy to mix up. Compare them on a team that holds a list of players.

from dataclasses import asdict, dataclass@dataclassclass Player:    name: str    goals: int@dataclassclass Team:    name: str    players: list[Player]team = Team("Owls", [Player("Ada", 3)])print(vars(team))print(asdict(team))

This prints {'name': 'Owls', 'players': [Player(name='Ada', goals=3)]}, then {'name': 'Owls', 'players': [{'name': 'Ada', 'goals': 3}]}. vars() returns the object's own storage, one level deep: the Player inside stays an object, and changing that dictionary changes team. asdict() builds a new list for players and turns each Player in it into a dictionary. Use asdict() to export, because it converts every level.

The export is a separate copy

asdict() builds new dictionaries and lists. A change to the object after the export does not reach it.

from dataclasses import asdict, dataclass@dataclassclass Player:    name: str    goals: int@dataclassclass Team:    name: str    players: list[Player]team = Team("Owls", [Player("Ada", 3)])data = asdict(team)team.players.append(Player("Sam", 1))print(len(team.players))print(len(data["players"]))

This prints 2, then 1. The export is a snapshot of the object at the moment you call asdict(). Finish building the object first, then export it. Changing data does not change team either.

Note: asdict() needs a dataclass object. asdict(team.players) raises TypeError: asdict() should be called on dataclass instances, because a list is not a dataclass. Pass the object that holds the list.

See also: Python JSON, Python Frozen Dataclasses and replace.

Your turn

Print the export of line as JSON text with json.dumps(). Then print the x of the end point, read from the export.

🎯 Goal — make it print exactly:
{"start": {"x": 0, "y": 0}, "end": {"x": 3, "y": 4}}
3
import jsonfrom dataclasses import asdict, dataclass@dataclassclass Point:    x: int    y: int@dataclassclass Line:    start: Point    end: Pointline = Line(Point(0, 0), Point(3, 4))# add three lines: export line with asdict(), print it as JSON text, then print the end point's x from the export