您的问题有点不清楚,但正如 cmets 中所建议的那样,最好将 single 模型作为代表您的组数据的数据类(即包含 data1 和data2 fields)并定义一个辅助函数,该函数构造组名到模型实例的映射,如下所示。
注意:这里假设您使用的是 Python 3.8+。对于早期版本,我会做两件事:
- 如果需要,请删除
__future__ 导入,而是从 typing 模块导入 Type 和 Dict,因为 Python 3.8 或更早版本中的内置类型不支持下标值。
- 删除 Python 3.8 中引入的 walrus
:= 运算符的用法,改为使用它后面的注释行。
# Future import to allow the `int | str` syntax below
# Can be removed for Python 3.10
from __future__ import annotations
from dataclasses import dataclass
from typing import TypeVar
# Create a type that can be `MyData`, or any subclass
D = TypeVar('D', bound='MyData')
@dataclass
class MyData:
data1: str
data2: str
@classmethod
def from_dict(cls: type[D], data: dict, group_num: int | str) -> D:
return cls(
data1=data['MG'][f'G {group_num}']['data1'],
data2=data['MG'][f'G {group_num}']['data2'],
)
@classmethod
def group_to_data(cls: type[D], data: dict) -> dict[int, D]:
return {(group_num := int(group_key.split()[-1])): cls.from_dict(
data, group_num)
for group_key in data['MG']}
# For Python 3.7 or lower, uncomment and use the below instead
# ret_dict = {}
# for group_key in data['MG']:
# group_num = int(group_key.split()[-1])
# ret_dict[group_num] = cls.from_dict(data, group_num)
#
# return ret_dict
测试代码:
def main():
from pprint import pprint
my_data = {
'MG': {
'G 1': {
'data1': 'hello',
'data2': 'World!',
},
'G 2': {
'data1': '',
'data2': 'Testing',
},
'G 3': {
'data1': 'hello 123',
'data2': 'world 321!'
}
}
}
group_to_data = MyData.group_to_data(my_data)
pprint(group_to_data)
# True
assert group_to_data[1] == MyData('hello', 'World!')
输出:
{1: MyData(data1='hello', data2='World!'),
2: MyData(data1='', data2='Testing'),
3: MyData(data1='hello 123', data2='world 321!')}