["python","json","dictionary","python-dataclasses"]
How to convert Python dataclass to dictionary of string literal?

Given a dataclass like below: class MessageHeader(BaseModel): message_id: uuid.UUID def dict(self, **kwargs): return json.loads(self.json()) I would like to get a dictionary of string literal when I call dict on MessageHeader The desired outcome of dictionary is like below: {'message_id': '383b0bfc-743e-4738-8361-27e6a0753b5a'} I want to avoid using 3rd party library like pydantic & I do not want to use json.loads(self.json()) as there are extra round trips Is there any better way to convert a dataclass to a dictionary with string literal like above?
You can use dataclasses.asdict: from dataclasses import dataclass, asdict class MessageHeader(BaseModel): message_id: uuid.UUID def dict(self): return {k: str(v) for k, v in asdict(self).items()} If you're sure that your class only has string values, you can skip the dictionary comprehension entirely: class MessageHeader(BaseModel): message_id: uuid.UUID dict = asdict