Creating class instances from a Dictionary in Python

avatar

Borislav Hadzhiev

Last updated: Sep 16, 2022

banner

Photo from Unsplash

Creating class instances from a Dictionary in Python #

To create class instances from a dictionary:

  1. Take a dictionary from the class's __init__() method.
  2. Iterate over the dictionary's items.
  3. Use the setattr method to assign each key-value pair as an instance attribute.
main.py
class Employee(): def __init__(self, dictionary): for key, value in dictionary.items(): setattr(self, key, value) my_dict = {'name': 'bobbyhadz', 'salary': 100, 'language': 'Python'} bob = Employee(my_dict) print(bob.name) # 👉️ bobbyhadz print(bob.salary) # 👉️ 100 print(bob.language) # 👉️ Python

The __init__() method takes a dictionary and sets its key-value pairs as instance attributes.

We used a for loop to iterate over the dictionary's items.

The dict.items method returns a new view of the dictionary's items ((key, value) pairs).

main.py
my_dict = {'id': 1, 'name': 'BobbyHadz'} print(my_dict.items()) # 👉️ dict_items([('id', 1), ('name', 'BobbyHadz')])

On each iteration, we use the setattr() function to set each key-value pair as an attribute on the instance.

The setattr() function takes the object, the attribute name and the value as arguments.

If your dictionary contains keys with spaces, use the str.replace() method to replace each space with an underscore.

main.py
class Employee(): def __init__(self, dictionary): for key, value in dictionary.items(): setattr(self, str(key).replace(' ', '_'), value) my_dict = {'first name': 'bobbyhadz', 'salary': 100, 'language': 'Python'} bob = Employee(my_dict) print(bob.first_name) # 👉️ bobbyhadz print(bob.salary) # 👉️ 100 print(bob.language) # 👉️ Python

The first name key contains a space, so we used the str.replace() method to replace any spaces in the dictionary's keys with underscores.

If you get linting errors when you try to access attributes on each instance, e.g. "Instance of 'Employee' type has no 'X' member", initialize the attributes to None.

main.py
class Employee(): def __init__(self, dictionary): self.name = None self.salary = None self.language = None for key, value in dictionary.items(): setattr(self, str(key).replace(' ', '_'), value) my_dict = {'name': 'bobbyhadz', 'salary': 100, 'language': 'Python'} bob = Employee(my_dict) print(bob.name) # 👉️ bobbyhadz print(bob.salary) # 👉️ 100 print(bob.language) # 👉️ Python

We initialized all attributes to None, so we can access the attributes on each instance without getting linting errors.

An alternative approach to consider is to define the properties in the __init__() method and unpack the dictionary's key-value pairs when instantiating the class.

main.py
class Employee(): def __init__(self, name, salary, language): self.name = name self.salary = salary self.language = language my_dict = {'name': 'bobbyhadz', 'salary': 100, 'language': 'Python'} bob = Employee(**my_dict) print(bob.name) # 👉️ bobbyhadz print(bob.salary) # 👉️ 100 print(bob.language) # 👉️ Python

We used the ** operator to unpack the key-value pairs of the dictionary when instantiating the class.

You can imagine that the dictionary's key-value pairs got passed as keyword arguments to the class, e.g. Employee(name='bobbyhadz', salary=100).

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.