@dataclass
class Car:
brand: str
color: str
How can I get a dict that ignore None values? Something like:
>>> car = Car(brand="Audi", color=None)
>>> asdict(car, some_option_to_ignore_none_values=True)
> {'brand': 'Audi'}
All answers are good but to me they are too verbose. Here's a one-liner:
# 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})
Show case:
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)}
Another option is to write a dict_factory that will reject adding None values and pass it to asdict
method.
checkout the code source here https://github.com/python/cpython/blob/master/Lib/dataclasses.py
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With