0

I know that sound generic, so I will try my best to explain the case.

I am getting back from a process, some data. I would like to organize this data in a format that I can interact with it, and access it.

So far I thought that I can make a simple class, which is empty, and at creation time it takes **kwargs and cycle trough them, adding them to the class.

Although I am not sure if this is the correct way to do so. Imagine the following data:

dict1={param1:a, param2:b, param3:c, param4:d}              #Operation1
dict2={param2:t, param1:2, param1:r}                        #Operation2
dict3={param1:1, param7:2, param2:4, param4:b, param3:m}    #Operation3

I would like to make a class that when creating, will take the parameters, resulting in the class attribute name taken from the parameter name, and as value, the value of that parameter:

myclass1(dict1)

myclass2.param1 return a, myclass1.param2 return b and so on

But if I want to make myclass using dict2, I can also do so:

myclass2(dict2)

myclass1.param2 return t, myclass2.param1 return 2 and so on

In this way I have a name with the parameter, and can retrieve it at later time, and at the same time I do not have to worry about how many element my data has, since the class will always get the number of parameters, and create class attributes, using the name of the key in the dictionary.

Is possible to achieve this in a simple way in python? I can use dictionary in a dictionary, but it feels utterly complicate, for big data sets.

1
  • Why not just use dict1 etc. directly? Do you need a class at all? Commented Apr 4, 2015 at 2:45

1 Answer 1

1

You can do something like:

In [2]: dict1={'param1':'a', 'param2':'b', 'param3':'c', 'param4':'d'}

In [3]: class A(object):
   ...:     def __init__(self, params):
   ...:         for k, v in params.iteritems():
   ...:             setattr(self, k, v)
   ...:

In [4]: a = A(dict1)

In [5]: a.param1
Out[5]: 'a'

In [6]: a.param2

Out[6]: 'b'
Sign up to request clarification or add additional context in comments.

1 Comment

This is good, but it's best to name the parameter something else besides hash because it shadows the built-in function of the same name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.