Sibi
Sibi

Reputation: 48756

Changing dictionary keys in class object

Let's assume I have the following class:

class Test:
    def __init__(self, a, b):
        self.a = a
        self.b = b

And I can convert that class to dictionary like this:

>>> a = Test(1,2)
>>> a.__dict__
{'a': 1, 'b': 2}

Now, I want to change the key of that dictionary to some other thing:

>>> a.__dict__
{'new_a': 1, 'new_b': 2}

Is there a proper way of achieving this by adding some new method in the class Test such that it will automatically covert them to the desired output ?

Upvotes: 1

Views: 275

Answers (2)

simonzack
simonzack

Reputation: 20938

Using __dict__ is the wrong approach, as __dict__ should not be modified if you do not want to change the underlying class. Add a method or property instead:

class Test:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    @property
    def json_dict(self):
        return dict(('new_' + name, value) for name, value in self.__dict__.items() if name != 'json_dict')

Test(1, 2).json_dict

Upvotes: 3

Luis Masuelli
Luis Masuelli

Reputation: 12343

No. Keys cannot be modified in a dictionary. What you should do is create a new dict (rather than modifying it in-place):

a = Test(1,2)
a.__dict__ = {afunc(k): v for (k, v) in a.__dict__}

If you want to change certain properties without iteration, you should:

a.__dict__['new_a'] = a.__dict__.pop('a')

disclaimer: I can't figure why should you need to alter the __dict__ in an instance - it does not seem to sound so pythonic.

Upvotes: 0

Related Questions