Search code examples
pythonpython-dataclasses

How to overwrite Python Dataclass 'asdict' method


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?


Solution

  • 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