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

标签 python python-3.x algorithm dictionary

我有以下数据类:

@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

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

最佳答案

根据 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'}

关于python - 如何从没有 None 字段的类创建字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57305749/

相关文章:

python - wtform 上的实时验证。我可以访问前端的验证器吗?

python - Python:Numpy.min替换了内置函数:导致Pyro4错误:回复序列不同步

python - 使用自定义转换类型扩展字符串格式

python - 双重跳出嵌套循环

django - Celery 使用 app.control.purge() 时运行任务会发生什么?

algorithm - 有效填充 3D 矩阵中的空单元

python - 如何在检查重复行标题和共同添加新数据时合并多个 csv 文件

python - 定义抽象类的三种方式的区别

c++ - 在 C/C++ 中查找字符串中具有任意字符顺序的子字符串

从搜索文档中找到最小片段的算法?