Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating class instance properties from a dictionary?

I'm importing from a CSV and getting data roughly in the format

{ 'Field1' : 3000, 'Field2' : 6000, 'RandomField' : 5000 } 

The names of the fields are dynamic. (Well, they're dynamic in that there might be more than Field1 and Field2, but I know Field1 and Field2 are always going to be there.

I'd like to be able to pass in this dictionary into my class allMyFields so that I can access the above data as properties.

class allMyFields:     # I think I need to include these to allow hinting in Komodo. I think.     self.Field1 = None     self.Field2 = None      def __init__(self,dictionary):         for k,v in dictionary.items():             self.k = v             #of course, this doesn't work. I've ended up doing this instead             #self.data[k] = v             #but it's not the way I want to access the data.  q = { 'Field1' : 3000, 'Field2' : 6000, 'RandomField' : 5000 } instance = allMyFields(q) # Ideally I could do this. print q.Field1 

Any suggestions? As far as why -- I'd like to be able to take advantage of code hinting, and importing the data into a dictionary called data as I've been doing doesn't afford me any of that.

(Since the variable names aren't resolved till runtime, I'm still going to have to throw a bone to Komodo - I think the self.Field1 = None should be enough.)

So - how do I do what I want? Or am I barking up a poorly designed, non-python tree?

like image 788
Rizwan Kassim Avatar asked Oct 28 '09 18:10

Rizwan Kassim


People also ask

How do you convert a dictionary to 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 a dictionary key be a class?

A dictionary is an object of class dict. It's an unordered collection means that while iterating the order of retrieval is not guaranteed. The dictionary keys and values can be of any type. They can also be None .

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.


1 Answers

You can use setattr (be careful though: not every string is a valid attribute name!):

>>> class AllMyFields: ...     def __init__(self, dictionary): ...         for k, v in dictionary.items(): ...             setattr(self, k, v) ...  >>> o = AllMyFields({'a': 1, 'b': 2}) >>> o.a 1 

Edit: let me explain the difference between the above code and SilentGhost's answer. The above code snippet creates a class of which instance attributes are based on a given dictionary. SilentGhost's code creates a class whose class attributes are based on a given dictionary.

Depending on your specific situation either of these solutions may be more suitable. Do you plain to create one or more class instances? If the answer is one, you may as well skip object creation entirely and only construct the type (and thus go with SilentGhost's answer).

like image 175
Stephan202 Avatar answered Oct 01 '22 07:10

Stephan202