我有以下数据类:
# model.py
from dataclasses import dataclass
from typing import Optional
@dataclass(frozen=True)
class Location:
x: int
y: int
def __lt__(self, other):
return self.x < other.x and self.y < other.y
@dataclass
class Group:
locations: set[Location]
name: str
我想将 Group 数据类序列化为 Python 字典对象。我尝试使用以下代码来实现此目的:
group = Group(locations={Location(x=0, y=1), Location(x=0, y=0)}, name='foo')
puzzle_dict = dataclasses.asdict(group)
但是当我这样做时,返回的字典看起来像
{'locations': {Location(x=0, y=1), Location(x=0, y=0)}, 'name': 'foo'}
而我想要
{'locations': {{'x': 1, 'y': 0}, {'x': 0, 'y': 0}}, 'name': 'foo'}
在单个
dataclasses.asdict
上调用 Location
会产生预期的行为,但在 dataclasses.asdict
上调用 Group
时,这不起作用。有什么建议吗?
好吧,您期望的输出是
{'locations': {{'x': 1, 'y': 0}, {'x': 0, 'y': 0}}, 'name': 'foo'}
但是仔细看看
locations
的值,它是一组Python不支持的字典。
>>> {{'x': 1, 'y': 0}, {'x': 0, 'y': 0}}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
您能做的最好的事情是将
set
更改为 list
,这将使 asdict
按预期工作。
>>> from dataclasses import dataclass
>>> import dataclasses
>>> from typing import Optional
>>>
>>>
>>> @dataclass(frozen=True)
... class Location:
... x: int
... y: int
...
>>>
>>> @dataclass
... class Group:
... locations: list[Location]
... name: str
...
>>> group = Group(locations=[Location(x=0, y=1), Location(x=0, y=0)], name='foo')
>>> puzzle_dict = dataclasses.asdict(group)
>>> print(puzzle_dict)
{'locations': [{'x': 0, 'y': 1}, {'x': 0, 'y': 0}], 'name': 'foo'}