Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add key to dict with setattr() in Python

Tags:

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.

like image 852
linkyndy Avatar asked Sep 23 '13 10:09

linkyndy


People also ask

What is Setattr () used for in Python?

The setattr() function sets the value of the specified attribute of the specified object.

What is __ Setattr __ in Python?

Python setattr() method is used to assign the object attribute its value.

How do I add an item to a dictionary key in Python?

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.

What is Setattr () and Getattr () used for?

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.


2 Answers

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

getattr(cls, 'fields')['key'] = 'value'
like image 197
Jon Clements Avatar answered Oct 01 '22 22:10

Jon Clements


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'}
like image 35
Sukrit Kalra Avatar answered Oct 01 '22 23:10

Sukrit Kalra