-1

I am using a set of Json objects to create set of dictionaries like this.

t = [{"A":100}, {"B":200}, {"C":300}]

Now I want them to cast in to a bigger dictionay in such a way that items no specified should take a default value.

default = {
        "A" : 10,
        "B" : 20,
        "C" : 30
        }

What I have tried so far is to use a class as follows

class MyClass:
    default = {
            "A" : 10,
            "B" : 20,
            "C" : 30
            }

    def __init__(self, input):
        self.default.update(input)

    def get(self):
        return self.default

But when i try to create a list of dictionaries like this, it gives wrong answer.

a = [MyClass(x).get() for x in t]
[{'A': 100, 'C': 300, 'B': 200}, {'A': 100, 'C': 300, 'B': 200}, {'A': 100, 'C': 300, 'B': 200}]

seems to me like only one class instance was generated and the init was called upon it instead of creating many instances. Can you please point out the error/suggest other ways of doing this ?

Thanks

ABCD
  • 153
  • 1
  • 10

1 Answers1

1

seems to me like only one class instance was generated

Because that's exactly what happened. All instances of MyClass have the same reference to the same dictionary. You should instantiate a new dictionary in your constructor:

class MyClass:
    def __init__(self, input):
        self.default = {
            "A" : 10,
            "B" : 20,
            "C" : 30
        }
        self.default.update(input)

    def get(self):
        return self.default
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
  • Hi @Derek, Thanks for the answer. My background is C/C++, so I have a little hard time understanding this. Shouldn't each call to MyClass constructor supposed to create new instances of the class MyClass. if not whats the purpose of having classes ? – ABCD Sep 24 '18 at 06:43
  • @ABCD If you have knowledge of C++, in your initial code you have created a static attribute, and remember C++ is not python, they do not have the same syntax. – eyllanesc Sep 24 '18 at 06:45
  • @ABCD Your code is equivalent to allocating memory for a dictionary structure, then initializing all `MyClass` to have a pointer pointing the same structure. You need to reallocate more memory for the structure in the constructor. That’s the same in both Python and C++. – Derek 朕會功夫 Sep 24 '18 at 11:34