Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Construct a dataclass from a dict with unexpected keys
from dataclasses import asdict, fields
from typing import Any, Dict
class DataClassBase:
def fromdict(cls, d: Dict[str, Any]):
"""Return a dataclass from a dict which may include unexpected keys."""
class_fields = { for f in fields(cls)}
return cls(**{k: v for k, v in d.items() if k in class_fields})
def asdict(self):
"""Return the fields of a dataclass instance as a new dictionary mapping field names to
field values."""
return asdict(self)
from dataclasses import dataclass
from dataclass_util import DataClassBase
class Person(DataClassBase):
name: str
age: int
person = Person.fromdict({'name': 'John Doe', 'age': 42, 'address': None})
print(person.asdict()) # {'name': 'John Doe', 'age': 42}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment