简体   繁体   中英

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:

{
    "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). How do I declare that in a dataclass in Python? It would essentially be str: str , but that would interpret the key as literally "str" instead of a type.

I personally feel the simplest approach would be to create a custom Container dataclass. 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. So for example, you could access the first string value like values[0] if you wanted to.

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'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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