Pydantic:如何将对象列表表示为 dict(将列表序列化为 dict)

问题描述 投票:0回答:1

在 Pydantic 中,我想将项目列表表示为字典。在该字典中,我希望该键是该项目的

id
作为字典的键。 我阅读了有关序列化映射类型序列的文档。

但是,我没有找到创建这样的表示的方法。

我希望我的 api 中的这些可以从生成的 api 客户端轻松访问。

class Item(BaseModel):
    uid: UUID = Field(default_factory=uuid4)
    updated: datetime = Field(default_factory=datetime_now)
    ...


class ResponseModel:
    ...


print ResponseModel.model_dump()
#> {
        "67C812D7-B039-433C-B925-CA21A1FBDB23": {
            "uid": "67C812D7-B039-433C-B925-CA21A1FBDB23", 
            "updated": "2024-05-02 20:24:00"
        },{
        "D39A8EF1-E520-4946-A818-9FA8664F63F6": {
            "uid": "D39A8EF1-E520-4946-A818-9FA8664F63F6",
            "updated":"2024-05-02 20:25:00"
        }
    }
python pydantic
1个回答
0
投票

你想要的很简单。只需使用字典理解,如下所示。

# represents your data
data = [{'id':'abc'}, {'id':'def'}]

# reformat to dict with ids for keys
ndata = {x['id']:x for x in data}

print(ndata)

输出

{'abc': {'id': 'abc'}, 'def': {'id': 'def'}}
© www.soinside.com 2019 - 2024. All rights reserved.