Reputation: 336
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?
Upvotes: 2
Views: 985
Reputation: 106883
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)
Upvotes: 2