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

Leave a Comment