1

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 ?

5
  • No, you must manually change the dict Commented Oct 14, 2014 at 14:20
  • 2
    Why do you need to "convert" the object to a dict in the first place? (Note that you aren't converting anything; you are just getting a reference to the dict object the class uses to store the values of instance attributes.) Commented Oct 14, 2014 at 14:21
  • You can certainly alter self.__dict__ in an instance method - is that what you mean? However, this is unlikely to be the "proper way" of doing whatever it is you're trying to achieve. Commented Oct 14, 2014 at 14:22
  • @chepner To convert them to json with sensible keys. Commented Oct 14, 2014 at 14:22
  • Maybe look into that. Commented Oct 14, 2014 at 14:25

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.