[Python] How to parse list of models with Pydantic

Discussão em 'Python' iniciado por Stack, Maio 19, 2025.

  1. Stack

    Stack Membro Participativo

    I use Pydantic to model the requests and responses to an API.

    I defined a User class:

    from pydantic import BaseModel

    class User(BaseModel):
    name: str
    age: int


    My API returns a list of users which I retrieve with requests and convert into a dict:

    users = [{"name": "user1", "age": 15}, {"name": "user2", "age": 28}]


    How can I convert this dict to a list of User instances?

    My solution for now is

    user_list = []
    for user in users:
    user_list.append(User(**user))

    Continue reading...

Compartilhe esta Página