Shivam Agrawal
Shivam Agrawal

Reputation: 95

Python Update an Object from Dictionary

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?

Upvotes: 1

Views: 192

Answers (1)

Dan Constantinescu
Dan Constantinescu

Reputation: 1526

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}")

Upvotes: 1

Related Questions