dict中具有不同密钥名称的dataclass



是否可以将键转换为数据类中的类属性?原因是dict中的键(我从JSON文件中截取(在JSON中没有匹配的属性名称(例如,下面示例中的_id必须变成id(。

使用下面的代码,我觉得我写的样板文件太多了。

字典:

{'_id': '5719fdf6edf5136d37aaf562', 'divespot': 'The Tugs', 'divesite': 'Fathom Five National Park', 'region': 'Ontario', 'country': 'Canada'}

类别:

class DiveSpot:
id: str
name: str
def from_dict(self, divespot):
self.id = divespot.get("_id")
self.name = divespot.get("divespot")
from dataclasses import dataclass
dskeymap = {'_id': 'id', 'divespot': 'name', 'divesite': 'site', 'region': 'region', 'country': 'country'}
data =  {'_id': '5719fdf6edf5136d37aaf562', 'divespot': 'The Tugs', 'divesite': 'Fathom Five National Park', 
'region': 'Ontario', 'country': 'Canada'}
@dataclass
class DiveSpot:
id: str
name: str
site: str
region: str
country: str
ds = DiveSpot(**{newk: data[oldk] for oldk, newk in dskeymap.items()})

打印ds给出

DiveSpot(id='5719fdf6edf5136d37aaf562', name='The Tugs', site='Fathom Five National Park', region='Ontario', country='Canada')

或添加@classmethod

@dataclass
class DiveSpot:
id: str
name: str
site: str
region: str
country: str
@classmethod
def fromdict(cls, d, keymap=dskeymap):
return cls(**{newk: data[oldk] for oldk, newk in dskeymap.items()})

您可以在创建数据类之前首先转换字典,例如:

divespot_dict = dict(divespot)
divespot_copy['id'] = divespot_dict['_id']
divespot = DiveSpot(**divespot_copy)

最新更新