Set attributes from dictionary in python
Sure, something like this:
class Employee(object):
def __init__(self, initial_data):
for key in initial_data:
setattr(self, key, initial_data[key])
Update
As Brent Nash suggests, you can make this more flexible by allowing keyword arguments as well:
class Employee(object):
def __init__(self, *initial_data, **kwargs):
for dictionary in initial_data:
for key in dictionary:
setattr(self, key, dictionary[key])
for key in kwargs:
setattr(self, key, kwargs[key])
Then you can call it like this:
e = Employee({"name": "abc", "age": 32})
or like this:
e = Employee(name="abc", age=32)
or even like this:
employee_template = {"role": "minion"}
e = Employee(employee_template, name="abc", age=32)
Setting attributes in this way is almost certainly not the best way to solve a problem. Either:
You know what all the fields should be ahead of time. In that case, you can set all the attributes explicitly. This would look like
class Employee(object): def __init__(self, name, last_name, age): self.name = name self.last_name = last_name self.age = age d = {'name': 'Oscar', 'last_name': 'Reyes', 'age':32 } e = Employee(**d) print e.name # Oscar print e.age + 10 # 42
or
You don't know what all the fields should be ahead of time. In this case, you should store the data as a dict instead of polluting an objects namespace. Attributes are for static access. This case would look like
class Employee(object): def __init__(self, data): self.data = data d = {'name': 'Oscar', 'last_name': 'Reyes', 'age':32 } e = Employee(d) print e.data['name'] # Oscar print e.data['age'] + 10 # 42
Another solution that is basically equivalent to case 1 is to use a collections.namedtuple
. See van's answer for how to implement that.