pythonpython-object

How to assign Python Dict Keys to corresponding Python Object Attributes


Suppose I have a python class like:

class User:
    name = None
    id = None
    dob = None
    
    def __init__(self, id):
        self.id = id

Now I am doing something like this:

userObj = User(id=12) # suppose I don't have values for name and dob yet
## some code here and this code gives me name and dob data in dictionary, suppose a function call
user = get_user_data() # this returns the dictionary like {'name': 'John', 'dob': '1992-07-12'}

Now, the way to assign data to user object is userObj.name = user['name'] and userObj.dob = user['dob']. Suppose, User has 100 attributes. I will have to explicitly assign these attributes. Is there an efficient way in Python which I can use to assign the values from a dictionary to the corresponding attributes in the object? Like, name key in the dictionary is assigned to the name attribute in the object.


Solution

  • class User(dict):
        def __init__(self, *args, **kwargs):
            super(User, self).__init__(*args, **kwargs)
            self.__dict__ = self
    

    and then just get your dictionary and do:

    userObj  = User(dictionary)
    

    EDIT: user the function setattr() then

    [setattr(userObj, key, item) for key,item in dict.items()]