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
?
We are calling a function here Dict2Class which takes our dictionary as an input and converts it to class. We then loop over our dictionary by using setattr() function to add each of the keys as attributes to the class. setattr() is used to assign the object attribute its value.
Is it possible to set a dictionary value to a class? Yes, it's possible.
If you want to use a dictionary globally within a class, then you need to define it in section where you use your class. if you are using your class in main, then define it there. A dictionary or o list are global by default. class Store: ...
The __dict__ in Python represents a dictionary or any mapping object that is used to store the attributes of the object. They are also known as mappingproxy objects. To put it simply, every object in Python has an attribute that is denoted by __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.
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
The other solution is to Filter dict to contain only certain keys:
dict_you_want = { your_key: dict[your_key] for your_key in your_keys }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With