Converting a python Dict into a class

← Posts · 07/12/2020 · 1 minute

In python, dictionnaries and classes behave differently. One of the main difference is how you access their members. In the following example, class_instance and dictionnary hold the same data.

class Foo:
  def __init__(self): = "foo"

class_instance = Foo()
dictionnary = {'bar': 'foo'}

print(, dictionnary['bar']) # foo foo

But in order to access the value of bar, the syntax is longer for the dictionnary and may not be convenient in cases where the class syntax is required. To quickly convert the dictionnary into a class, you can use the following code:

new_class = type('D', (object,), dictionnary)()
print( # foo

Under the hood, it will construct a class called D and build it using the dictionnary’s key/value pairs.