Skip to content

Instantly share code, notes, and snippets.

@brettvitaz
Created February 9, 2023 23:01
Show Gist options
  • Save brettvitaz/9b19aa9bf12d95397f222e5881c4d505 to your computer and use it in GitHub Desktop.
Save brettvitaz/9b19aa9bf12d95397f222e5881c4d505 to your computer and use it in GitHub Desktop.
Prune dict for dataclass
def prune_dict_for_dataclass(d: dict, cls):
ret = {}
for field in fields(cls):
if field.name in d:
if is_dataclass(field.type):
ret[field.name] = prune_dict_for_dataclass(d[field.name], field.type)
elif typing.get_origin(field.type) is list and type(d[field.name]) is list:
list_cls = typing.get_args(field.type)[0]
if is_dataclass(list_cls):
ret[field.name] = [prune_dict_for_dataclass(i, list_cls) for i in d[field.name]]
else:
ret[field.name] = d[field.name]
else:
ret[field.name] = d[field.name]
return ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment