1

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?

Data Mastery
  • 1,555
  • 4
  • 18
  • 60

1 Answers1

2

Use setattr

class Test:
    pass

test = Test()

for x in ["a", "b", "c"]:
    setattr(test,x,x)
    
print(test.__dict__)
bn_ln
  • 1,648
  • 1
  • 6
  • 13