Python Update an Object from Dictionary

Viewed 44

I have an object User, and I have a dictionary of attributes that needs to be updated like data={'name':"Tom",'age':26} I want to iterate over the dictionary and update it Something like this:

for key,val in data.items():
    user.key=val

The problem is it is saying user have no attribute as key. I want to replace user.key as user.name="Tom"

Any solution to it?

1 Answers

You can achieve this using setattr function:

class User:
    pass


data = {"name": "Tom", "age": 26}

user = User()

for key, value in data.items():
    setattr(user, key, value)

print(f"Name: {user.name}, Age: {user.age}")
Related