0

For example I have a pydantic model, like this:

class Person:
   name:str
   age: int
   city: str

With pydantic we can get the value by using: P1.name -for example P1 already exists as an instance- My question is that I have a P1 and I have a string.

P1 = People[name='Steve', age=22, city='New York']
data = "city"

How can I get the field named city with that data string, which will return New York?

jhsznrbt
  • 133
  • 1
  • 13

1 Answers1

0
try:
    res = getattr(P1, data)
except AttributeError:
    # no such attribute for p1
    res = None
print(f"{res=}")
Nikita
  • 376
  • 1
  • 10