Blue Moon
Blue Moon

Reputation: 4681

how to assign self.attributes in a class in a for loop?

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

Answers (3)

blhsing
blhsing

Reputation: 107124

You can update self.__dict__:

self.__dict__.update(tables_metadata)

Upvotes: 1

blue note
blue note

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

Michael
Michael

Reputation: 539

You can use setattr:

class TestClass:
    def __init__(self, name):
        tables_metadata = json.loads(jsonfilepath)

        self.name = name
        for key, value in tables_metadata.items:
            setattr(self, key, value)

Upvotes: 3

Related Questions