I have data with a nested dict containing IDs as keys and data objects as values. I am trying to convert this into a pydantic model.
Sometimes there is a need to access a nested value if it exists. However, making an if check every time when accessing a nested object is very verbose. E.g.:
from typing import Dict
from pydantic import BaseModel
class EventModel(BaseModel):
eventId: str
eventName: str
class UserModel(BaseModel):
userId: str
events: Dict[str, EventModel]
user_dict = {
'userId': 'abc',
'events': {
'xyz': {'eventId': 'xyz', 'eventName': 'User log in'},
'123': {'eventId': '123', 'eventName': 'User log out'},
},
}
user = UserModel(**user_dict)
unknown_id = '987'
# Inconvenient access pattern if there are multiple nested ID maps on the way
if user.events.get(unknown_id):
print(user.events[unknown_id].eventName)
# Compare to the more convenient dict access pattern
print(user_dict['events'].get(unknown_id, {}).get('eventName'))
If the object is deep, the access pattern with if statements become very ugly.
Is there a more convenient way to access nested values with ID mappings on the way using pydantic? Or is there a way to improve this pydantic model to be more scalable without changing the underlying data structure?