Search code examples
pythonpython-dataclasses

dataclasses: how to ignore None values using asdict()?


@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'}

Solution

  • 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)}