Content · Programming · Python

Python dataclasses.asdict() Function: Usage and Examples

Convert a dataclass instance into a dictionary with dataclasses.asdict().

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Convert a dataclass instance into a dictionary with dataclasses.asdict().

What You Will Learn


asdict(instance) recurses into nested dataclasses and standard collections and deep-copies many other objects. It is useful for structured export, but may cost memory and does not automatically make arbitrary values JSON serializable.

For only top-level fields, use a comprehension over dataclasses.fields().

Step-by-Step Example


The example below makes the behavior visible with small input values that you can change safely.

from dataclasses import dataclass, asdict

@dataclass
class Address:
    city: str

@dataclass
class Customer:
    name: str
    address: Address

customer = Customer("Taylor", Address("Haifa"))
print(asdict(customer))

How the Example Works


  • The imports provide the standard-library tools used in the demonstration: dataclasses.
  • The definitions Address, Customer separate the main steps into named components; calls to those components drive the example.
  • The variable customer holds the result of Customer('Taylor', Address('Haifa')). Later lines use that value or inspect how it changes.
  • The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.

For the chosen input, the expression asdict(customer) prints {'name': 'Taylor', 'address': {'city': 'Haifa'}}. Compare that result with the rule above before you change the argument.

Expected output from the example:

{'name': 'Taylor', 'address': {'city': 'Haifa'}}

When You Would Use This


These tools are useful when composing small reusable functions, adapting callbacks, or eliminating repeated work. Pay attention to whether the operation returns a new object, updates state, or produces lazy results. Test a small success case and a boundary case before integrating it into an application.

Practice: Modify the Code


Serialize a nested customer record to a Python dict.

Verify the changed output against the behavior described above, including the relevant invalid or boundary case.

For complete parameters and version details, consult the official Python documentation.

Common Beginner Mistakes


  • Assuming asdict() is a shallow view that shares nested mutable objects.
  • Expecting arbitrary Python objects in the result to be automatically JSON serializable.

Key Takeaways


  • Convert a dataclass instance into a dictionary with dataclasses.asdict().
  • asdict(instance) recurses into nested dataclasses and standard collections and deep-copies many other objects.
  • For only top-level fields, use a comprehension over dataclasses.fields().
Share this resourceSend this page to someone who may find it useful.