2

What am I trying to solve: I want to create an object that is based on a dictionary. The object should contain some additional methods that are out of the scope of this question. There dictionary passed must contain a known set of keys.

What obviously will work is:

   class DictBasedObject(object):
      def __init__(self, dictionary: {})
         if 'known_key_1' in dictionary:
            self.known_key_1 = dictionary['known_key_1']
         if 'known_key_2' in dictionary:
            self.known_key_2 = dictionary['known_key_2']
         ...

however this way is rather cumbersome.

How I am trying to solve: I would like to pass the dictionary as argument to a method, but with possibly specifying of the dictionary key-names/value-types, like:

   class DictBasedObject(object):
      def __init__(self, dictionary: {'known_key_1': str,
                                      'known_key_2': int,
                                      ...})
         self.known_key_1 = dictionary['known_key_1']
         self.known_key_2 = dictionary['known_key_2']
         ...

Obviously not much better, but at least one step towards 'more elegant'.

Is there an elegant and pythonic manner to solve this?

jpp
  • 159,742
  • 34
  • 281
  • 339
glamredhel
  • 336
  • 3
  • 12
  • If the dictionary must contain a known set of keys, why do you need to check they exist, i.e. can't you can get rid of the `if` statements in your first example? – jpp Jul 30 '18 at 12:49
  • 1
    I think I formulated the question not precisely enough. When saying _the dictionary must contain a known set of keys_ I meant something like a method's list of required arguments. Therefore - in case any of those keys are missing - the __init__ method should fail. – glamredhel Jul 30 '18 at 13:07

1 Answers1

2

You can either use the setattr function:

for k, v in dictionary.items():
    setattr(self, k) = v

or simply update the __dict__ attribute of the object:

self.__dict__.update(dictionary)
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • this does solve the problem of setting the object variables. Is there also a way of verifying that the dictionary has a given set of keys when it is being passed as argument? – glamredhel Jul 30 '18 at 13:09
  • 1
    You can use set difference for such a check: `if set('known_key_1', 'known_key_2') - dictionary.keys(): print('missing keys')` – blhsing Jul 30 '18 at 13:13