0

Suppose I want to initialize 50 variables in a Python class. I'd like to do this by loading a dict where each key/value pair corresponds to a self.key = value statement, which are all initialized to None by default.

The code I have right now is:

    def load_values(self, values):
        for k, v in values.iteritems():  
            if k in self.__dict__.keys(): # if the key in the dict matches a previously
                                          # initialized attribute
                self.k = v

This doesn't work because Python thinks k is the name of an attribute, which it is not. How can I make this work? I am running Python 2.7.

martineau
  • 119,623
  • 25
  • 170
  • 301
adamcircle
  • 694
  • 1
  • 10
  • 26

1 Answers1

3

I would use **kwargs and setattr:

class Foo(object):

    def load_values(self, **kwargs):
        for key, value in kwargs.iteritems():
            setattr(self, key, value)


foo = Foo()
foo.load_values(egg='bacon', sausages='spam')
# or
foo.load_values(**{'egg': 'bacon', 'sausages': 'spam'})

print(foo.egg) # bacon
print(foo.sausages) # spam
Arount
  • 9,853
  • 1
  • 30
  • 43