简体   繁体   English

Pydantic - 如何添加一个不断更改其名称的字段?

[英]Pydantic - How to add a field that keeps changing its name?

I am working with an API that is returning a response that contains fields like this:我正在使用返回包含如下字段的响应的 API:

{
    "0e933a3c-0daa-4a33-92b5-89d38180a142": someValue
}

Where the field name is a UUID that changes depending on the request (but is not included in the actual request parameters).其中字段名称是根据请求更改的 UUID(但不包含在实际请求参数中)。 How do I declare that in a dataclass in Python?如何在 Python 的数据类中声明它? It would essentially be str: str , but that would interpret the key as literally "str" instead of a type.它本质上是str: str ,但这会将键解释为字面上的“str”而不是类型。

I personally feel the simplest approach would be to create a custom Container dataclass.我个人觉得最简单的方法是创建一个自定义的Container数据类。 This would then split the dictionary data up, by first the keys and then individually by the values .然后,这会将字典数据拆分,首先是,然后是

The one benefit of this is that you could then access the list by index value instead of searching by the random uuid itself, which from what I understand is something you won't be doing at all.这样做的一个好处是,您可以通过索引值访问列表,而不是通过随机 uuid 本身进行搜索,据我了解,这是您根本不会做的事情。 So for example, you could access the first string value like values[0] if you wanted to.因此,例如,如果您愿意,您可以访问第一个字符串值,如values[0]

Here is a sample implementation of this:这是一个示例实现:

from dataclasses import dataclass


@dataclass(init=False, slots=True)
class MyContainer:

    ids: list[str]
    # can be annotated as `str: str` or however you desire
    values: list[str]

    def __init__(self, input_data: dict):
        self.ids = list(input_data)
        self.values = list(input_data.values())

    def orig_dict(self):
        return dict(zip(self.ids, self.values))


input_dict = {
    "0e933a3c-0daa-4a33-92b5-89d38180a142": "test",
    "25a82f15-abe9-49e2-b039-1fb608c729e0": "hello",
    "f9b7e20d-3d11-4620-9780-4f500fee9d65": "world !!",
}

c = MyContainer(input_dict)
print(c)

assert c.values[0] == 'test'
assert c.values[1] == 'hello'
assert c.values[2] == 'world !!'

assert c.orig_dict() == input_dict

Output:输出:

MyClass(values=['test', 'hello', 'world !!'], ids=['0e933a3c-0daa-4a33-92b5-89d38180a142', '25a82f15-abe9-49e2-b039-1fb608c729e0', 'f9b7e20d-3d11-4620-9780-4f500fee9d65'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM