How can I add a key to an object's dictionary with setattr()
? Say I have the fields
dictionary defined in my class. From another class I would like to add a key to this dictionary. How do I proceed? setattr(cls, 'fields', 'value')
changes the attribute entirely.
The setattr() function sets the value of the specified attribute of the specified object.
Python setattr() method is used to assign the object attribute its value.
If you want to add a new key to the dictionary, then you can use the assignment operator with the dictionary key. This is pretty much the same as assigning a new value to the dictionary. Since Python dictionaries are mutable, when you use the assignment operator, you're simply adding new keys to the datastructure.
Python setattr() and getattr() goes hand-in-hand. As we have already seen what getattr() does; The setattr() function is used to assign a new value to an object/instance attribute.
You don't, if you need to go down the name lookup route, then you use:
getattr(cls, 'fields')['key'] = 'value'
You should use getattr
instead of setattr
to do this. Something like.
>>> class TestClass:
def __init__(self):
self.testDict = {}
>>> m = TestClass()
>>> m.testDict
{}
>>> getattr(m, "testDict")["key"] = "value"
>>> m.testDict
{'key': 'value'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With