如何从没有None字段的类中创建字典? [英] How to create dict from class without None fields?
本文介绍了如何从没有None字段的类中创建字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我具有以下数据类:
@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
列出所有字段.
Is there any way to simplify to_dict
method? I don't want to list all of the fields using if
.
推荐答案
根据 meowgoesthedog 的建议,您可以使用 asdict
并过滤结果以跳过错误值:
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'}
这篇关于如何从没有None字段的类中创建字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文