Reputation: 4681
I have a class in which I read a json into a dictionary and I want to assign in a loop self.variable based on the key-value pairs in the dictionary as in:
class TestClass:
def __init__(self, name):
tables_metadata = json.loads(jsonfilepath)
self.name = name
for key, value in tables_metadata.items:
self.key = value
How can I pass the key value of the dictionary as the self.name_of_the_variable?
Upvotes: 0
Views: 1643
Reputation: 107124
You can update self.__dict__
:
self.__dict__.update(tables_metadata)
Upvotes: 1
Reputation: 29099
You can use setattr(self, key, value)
.
However, I don't know your use case, but in most cases it's probably better to just store the actual dict as attribute.
Upvotes: 1