#๐ Hi all,
7 messages ยท Page 1 of 1 (latest)
@edgy python
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
Closes after a period of inactivity, or when you send !close.
Not sure, but I think you should try creating another model called Address and using it as a field in Person?
Thanks for pointing me in the right direction, it works with this code:
from typing import Any
from pydantic import BaseModel, model_validator
person_data: dict[str, Any] = {
"first_name": "Jane",
"last_name": "Doe",
"date_of_birth": "1990-05-15",
"street_name": "Maple Street",
"house_number": 42,
"zip_code": "12345",
"city": "Miami",
"income": 100000,
}
class Address(BaseModel):
street_name: str
house_number: int
zipcode_code: str
city: str
class Person(BaseModel):
first_name: str
last_name: str
date_of_birth: str
address: Address
income: int
@model_validator(mode="before")
def build_nested_address(cls, values: dict) -> dict:
# Create a copy of the original flat dict for the root model
result = values.copy()
# Create the nested address structure using the same flat dict
result["address"] = values
return result
person = Person(**person_data)
print(person.model_dump_json(indent=4))
@edgy python Nice one! Well done.
This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.