linkyndy
linkyndy

Reputation: 17928

Add key to dict with setattr() in Python

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.

Upvotes: 8

Views: 17773

Answers (4)

3i10
3i10

Reputation: 1

Well you don't need setattr() to add a new key value pair into a dictionary like attribute.

All you need is:

obj.dictionary_name[key] = value
# type(key) : str

Although if you intend to use setattr() due to some reason, you can use:

getattr(obj,"dictionary_name")[key] = value

Advantage being you can use this in a setter or in some class method along with some code, whereas in the earlier method you cannot.

Although I found great use of this when I had to do something like this:

obj.f"_{dictionary_name}[{key}]" = value

For a fact it's known you cannot use string to access instance attribute.

So I tried:

setattr(obj,f"_{dictionary_name}[{key}]",value)
# this creates a new instance attribute.
# assume dictionary_name is example, key is color and value is red
# obj.__dict__ will contain '_example[color]' : 'red' instead of '_example' : {'color' : 'red'}

Here is the fix:

getattr(obj,f"_{dictionary_name}")[key] = value

Upvotes: 0

Erik Kaplun
Erik Kaplun

Reputation: 38257

How about cls.fields['key'] = 'value'.

Upvotes: 1

Sukrit Kalra
Sukrit Kalra

Reputation: 34531

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'}

Upvotes: 2

Jon Clements
Jon Clements

Reputation: 142256

You don't, if you need to go down the name lookup route, then you use:

getattr(cls, 'fields')['key'] = 'value'

Upvotes: 8

Related Questions