Search code examples
pythondictionaryclassarguments

feed a dictionary-like argument to a class


I am using a package where I need to build a class object for each of my experiments (many) and each time I need to feed too many variables into the class.

the class source code looks like:

.
.
.
def __init__(self, **kwargs):
        keys_to_set = [
            'key1',
            'key2',
            'key3',
            .
            .
            'keyN']
.
.
.

Now, I want to create .csv files for each experiment, and feed the class through an automated manner e.g. with a dictionary, however dictionary as arguments does not work for me and get errors!

I'm out of ideas, I don't know if there are any "dictionary-like" structures that may help me here. any helps/tips would be appreciated!

to make it a bit clear maybe:

if I want to make an object like test_obj like this:

test_obj = Class(key1=val1,
                 key2=val2,
                 .
                 .
                 keyN=valN)

is there any way that I can pass the argument as a dictionary-type thing like:

test_dict = {key1: val1, ...., keyN: valN}
test_obj = Class(test_dict)

(apparently dictionary can not do the job as I have tested)


Solution

  • I think you are looking to do one of these two things:

    This creates an instance based completely on passing a dictionary.

    class Foo():
        def __init__(self, data):
            for key, value in data.items():
                self.__setattr__(key, value)
    foo = Foo({"foo": 1, "bar": 2})
    print(foo.foo, foo.bar)
    

    Alternatively, this does the same in this particular case.

    class Foo():
        def __init__(self, data):
            self.__dict__ = data
    foo = Foo({"foo": 1, "bar": 2})
    print(foo.foo, foo.bar)
    

    Perhaps though, your constructor is less dynamic and you want to pass it key value pairs based on a dictionary. In that case you might:

    class Bar():
        def __init__(self, foo, bar):
            self.foo = foo
            self.bar = bar
    bar = Bar(**{"foo": 1, "bar": 2})
    print(bar.foo, bar.bar)
    

    All examples should result in:

    1 2