如何从没有None字段的类中创建字典?

pet*_*ush 5 python algorithm dictionary python-3.x

我有以下数据类:

@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
Run Code Online (Sandbox Code Playgroud)

有什么方法可以简化to_dict方法吗?我不想使用列出所有字段if

jde*_*esa 5

正如meowgoesthedog所建议的,您可以使用asdict并过滤结果来跳过虚假值:

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'}
Run Code Online (Sandbox Code Playgroud)