Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating class instance from dictionary?

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?

like image 517
Demyanov Avatar asked May 08 '15 00:05

Demyanov


People also ask

How do you turn a dictionary into a class?

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.

Can a dictionary value be a class?

Is it possible to set a dictionary value to a class? Yes, it's possible.

Can you put a dictionary in a class Python?

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

What is the use of __ dict __ in Python?

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


2 Answers

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
like image 67
Paul Rooney Avatar answered Oct 14 '22 13:10

Paul Rooney


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 }
like image 38
Brent Washburne Avatar answered Oct 14 '22 14:10

Brent Washburne