Creating class instance from dictionary?
Use a classmethod
to filter the dict and return the object.
You then dont have to force your __init__
method to accept a dict.
import itertools
class MyClass(object):
@classmethod
def fromdict(cls, d):
allowed = ('key1', 'key2')
df = {k : v for k, v in d.iteritems() if k in allowed}
return cls(**df)
def __init__(self, key1, key2):
self.key1 = key1
self.key2 = key2
dict = {'key1': 'value1', 'key2': 'value2', 'redundant_key': 'redundant_value'}
ob = MyClass.fromdict(dict)
print ob.key1
print ob.key2