CodeBlanks Logo Icon CodeBlanks

asdict and astuple

Learn conversion with dataclasses.asdict and astuple.

asdict and astuple

The asdict and astuple functions in the dataclasses module convert a dataclass instance to a dict and a tuple respectively. This is useful for passing data in another form.

Example: asdict(p) returns {'x': 3, 'y': 4}; astuple(p) returns (3, 4). Both are imported from the dataclasses module. These conversions are common when exporting data to a dict-expecting API or a database.

Which format for what?

asdict fits when you export data to a dict-expecting API; the keys are the field names. astuple fits when you need ordered access or pass data by position to a function.

Example: you can save a Point instance with save_dict(asdict(p)) and unpack it to a distance function with distance(*astuple(p)). Neither conversion changes the original instance; a new object is returned.

Practice Convert Point to dict and tuple

Start with from dataclasses import dataclass, asdict, astuple. Define a Point class with @dataclass; include fields x: int = 0 and y: int = 0. Then create an instance with p = Point(3, 4) and call print(asdict(p)) and print(astuple(p)).

Starter code

main.py
# Convert the Point instance with asdict and astuple

Sample solution

main.py
# Convert the Point instance with asdict and astuple
from dataclasses import dataclass, asdict, astuple

@dataclass
class Point:
    x: int = 0
    y: int = 0

p = Point(3, 4)
print(asdict(p))
print(astuple(p))

Expected output

{'x': 3, 'y': 4}
(3, 4)

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does asdict(p) return?

  • A list
  • A tuple
  • A dict Correct answer
  • A set

Explanation: asdict converts the instance to a dict.

2 Complete the import line

Question
from dataclasses import dataclass, ____

@dataclass
class Point:
    x: int = 0
    y: int = 0
Answer
from dataclasses import dataclass, asdict, astuple

@dataclass
class Point:
    x: int = 0
    y: int = 0

Explanation: asdict and astuple are imported together.

3 Match the conversion functions

Term Meaning
asdict Converts to dict
astuple Converts to tuple
{'x': 3, 'y': 4} Dict result
(3, 4) Tuple result

All lessons in Intermediate