I am trying to create class instance from dictionary that has keys more than class has attributes. I already read answers on the same question from this link: Creating class instance properties from a dictionary?. The problem is that I can't write __init__
in class definition as I want, because I'm using SQLAlchemy declarative style class definition. Also type('className', (object,), dict)
creates wrong attributes that are not needed.
Here is the solution that I found:
dict = {'key1': 'value1', 'key2': 'value2'}
object = MyClass(**dict)
But it does not work if dict has redundant keys:
dict = {'key1': 'value1', 'key2': 'value2', 'redundant_key': 'redundant_value'}
object = MyClass(**dict) # here need to ignore redundant_key
Are there any solutions except direct deleting all redundant keys from dict
?
Use a
classmethod
to filter the dict and return the object.You then dont have to force your
__init__
method to accept a dict.The other solution is to Filter dict to contain only certain keys:
One of the special python magic methods of an object is
object.__dict__
"A dictionary or other mapping object used to store an object’s (writable) attributes." So, by elevating this feature...Note: It doesn't handle nested dictionary...