Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create dict from class without None fields?

I have the following dataclass:

@dataclass
class Image:
    content_type: str
    data: bytes = b''
    id: str = ""
    upload_date: datetime = None
    size: int = 0

    def to_dict(self) -> Dict[str, Any]:
        result = {}
        if self.id:
            result['id'] = self.id
        if self.content_type:
            result['content_type'] = self.content_type
        if self.size:
            result['size'] = self.size
        if self.upload_date:
            result['upload_date'] = self.upload_date.isoformat()
        return result

Is there any way to simplify to_dict method? I don't want to list all of the fields using if.

like image 380
petrush Avatar asked Oct 16 '22 12:10

petrush


1 Answers

As suggested by meowgoesthedog, you can use asdict and filter the result to skip falsy values:

from dataclasses import dataclass, asdict
from datetime import datetime
from typing import Dict, Any

@dataclass
class Image:
    content_type: str
    data: bytes = b''
    id: str = ""
    upload_date: datetime = None
    size: int = 0

    def to_dict(self) -> Dict[str, Any]:
        return {k: v for k, v in asdict(self).items() if v}

print(Image('a', b'b', 'c', None, 0).to_dict())
# {'content_type': 'a', 'data': b'b', 'id': 'c'}
like image 58
jdehesa Avatar answered Oct 19 '22 23:10

jdehesa