gpt4 book ai didi

python - 数据类 : how to ignore None values using asdict()?

转载 作者:行者123 更新时间:2023-12-01 00:47:30 29 4
gpt4 key购买 nike

@dataclass
class Car:
brand: str
color: str

如何获得忽略 None 值的字典?像这样的东西:

>>> car = Car(brand="Audi", color=None)
>>> asdict(car, some_option_to_ignore_none_values=True)
> {'brand': 'Audi'}

最佳答案

所有答案都很好,但对我来说它们太冗长了。这是一句话:

# dc is dataclass
# d is dict out
d = asdict(dc, dict_factory=lambda x: {k: v for (k, v) in x if v is not None})

展示案例:

from typing import Optional, Tuple
from dataclasses import asdict, dataclass

@dataclass
class Space:
size: Optional[int] = None
dtype: Optional[str] = None
shape: Optional[Tuple[int]] = None

s1 = Space(size=2)
s1_dict = asdict(s1, dict_factory=lambda x: {k: v for (k, v) in x if v is not None})
print(s1_dict)
# {"size": 2}

s2 = Space(dtype='int', shape=(2, 5))
s2_dict = asdict(s2, dict_factory=lambda x: {k: v for (k, v) in x if v is not None})
print(s2_dict)
# {"dtype": "int", "shape": (2, 5)}

关于python - 数据类 : how to ignore None values using asdict()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56839030/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com