Creating class instance properties from a dictionary?
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.a1
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).
>>> q = { 'Field1' : 3000, 'Field2' : 6000, 'RandomField' : 5000 }>>> q = type('allMyFields', (object,), q)>>> q.Field13000
docs for type
explain well what's going here (see use as a constructor).
edit: in case you need instance variables, the following also works:
>>> a = q() # first instance>>> a.Field13000>>> a.Field1 = 1>>> a.Field11>>> q().Field1 # second instance3000
You can also use dict.update
instead of manually looping over items
(and if you're looping, iteritems
is better).
class allMyFields(object): # note: you cannot (and don't have to) use self here Field1 = None Field2 = None def __init__(self, dictionary): self.__dict__.update(dictionary)q = { 'Field1' : 3000, 'Field2' : 6000, 'RandomField' : 5000 }instance = allMyFields(q)print instance.Field1 # => 3000print instance.Field2 # => 6000print instance.RandomField # => 5000