I'd like to initialize A from a dict which can contain unexpected keys. I'd like to initialize with the given, known keys and ignore the rest
from dataclasses import dataclass
@dataclass
class A:
a: str
b: int
a1 = A(**{'a': 'Foo', 'b': 123}) # works
a2 = A(**{'a': 'Foo', 'b': 123, 'c': 'unexpected'}) # raises TypeError
Is there a Python feature that I'm missing or do I have to filter the dict upfront?
Another option is to use the dataclasses.fields function with a classmethod.
from dataclasses import dataclass, fields
@dataclass
class A:
a: str
b: int
@classmethod
def from_dict(cls, d: dict) -> "A":
field_names = {field.name for field in fields(cls)}
return cls(**{k: v for k, v in d.items() if k in field_names})
a1 = A.from_dict({'a': 'Foo', 'b': 123})
a2 = A.from_dict({'a': 'Foo', 'b': 123, 'c': 'unexpected, but who cares?'})
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