Python – set attributes dynamically in for loop

Question:

I have the following code:

class Test:
    pass

test = Test()

for x in ["a", "b", "c"]:
    test.x = x
    
print(test.__dict__)

{'x': 'c'}

This is not what I want. What I want is to set the name of the attribute corresponding to the value of the iteration:

Desired:

print(test.__dict__)
   
{'a': 'a', 'b': 'b', 'c': 'c'}

How can I do that?

Asked By: Data Mastery

||

Answers:

Use setattr

class Test:
    pass

test = Test()

for x in ["a", "b", "c"]:
    setattr(test,x,x)
    
print(test.__dict__)
Answered By: bn_ln
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.