10

I have a dataclass, which looks like this:

@dataclass
class myClass:
   id: str
   mode: str
   value: float

This results in:

dataclasses.asdict(myClass)
{"id": id, "mode": mode, "value": value}

But what I want is

{id:{"mode": mode, "value": value}}

I thought I could achive this by adding a to_dict method to my dataclass, which returns the desired dict, but that didn't work.

How could I get my desired result?

Markus
  • 125
  • 1
  • 6
  • What did you think about the [examples](https://docs.python.org/3/library/dataclasses.html#dataclasses.asdict) of usage in the documentation? – quamrana Oct 19 '20 at 06:52
  • That would leave me with the string "id" instead of the value of myClass.id as the first Key, right? Sorry, I am a total beginner :D – Markus Oct 19 '20 at 07:16
  • Ok, I see what you mean about `"id"`. So adding a `to_dict()` method will produce anything you want. In what way did that not work? – quamrana Oct 19 '20 at 07:40
  • adding a "to_dict(self)" method to myClass doesn't change the output of dataclasses.asdict(myClass). If I call the method by myClass.to_dict() it works – Markus Oct 19 '20 at 07:56
  • So just call `myClass.to_dict()` instead. – quamrana Oct 19 '20 at 07:57
  • That was the original plan anyway. The Problem is, that other programmers use my class and using it should be "foolproof", so asdict(myClass) and myClass.to_dict() should return the same – Markus Oct 19 '20 at 08:00

1 Answers1

6
from dataclasses import dataclass, asdict


@dataclass
class myClass:
    id: str
    mode: str
    value: float


def my_dict(data):
    return {
        data[0][1]: {
            field: value for field, value in data[1:]
        }
    }


instance = myClass("123", "read", 1.23)

data = {"123": {"mode": "read", "value":  1.23}}

assert asdict(instance, dict_factory=my_dict) == data
Evgeniy_Burdin
  • 627
  • 5
  • 14
  • 5
    Is there a overload/override asdict function instead? I need to alter asdict behaviour for some nested dataclasses, but not others. – Andrej Jul 21 '22 at 08:40
  • I have a similar requirement. Did you get any way to overload/override asdict function ? – Sagar Sahni Jan 31 '23 at 12:19