Creating class instance from dictionary?

2020-07-06 08:50发布

问题:

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?

回答1:

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


回答2:

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 }


回答3:

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...

class MyClass(object):
   def __init__(self, **entries):
      self.__dict__.update(entries))

dict = {'key1': 'value1', 'key2': 'value2', 'redundant_key': 'redundant_value'}

ob = MyClass(**dict)

Note: It doesn't handle nested dictionary...