Creating class instances from a Dictionary in Python

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
3 min

banner

# 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 Developer(): def __init__(self, dictionary): for key, value in dictionary.items(): setattr(self, key, value) my_dict = {'name': 'bobbyhadz', 'salary': 50, 'language': 'Python'} bob = Developer(my_dict) print(bob.name) # ๐Ÿ‘‰๏ธ bobbyhadz print(bob.salary) # ๐Ÿ‘‰๏ธ 50 print(bob.language) # ๐Ÿ‘‰๏ธ Python

create class instances from dictionary

The code for this article is available on GitHub

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 = {'name': 'bobbyhadz', 'salary': 50, 'language': 'Python'} # ๐Ÿ‘‡๏ธ dict_items([('name', 'bobbyhadz'), ('salary', 50), ('language', 'Python')]) print(my_dict.items())

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

main.py
for key, value in dictionary.items(): setattr(self, key, value)

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

# Taking keyword arguments when creating an instance

You can also tweak the __init__() method to take keyword arguments after the dictionary.

main.py
class Developer(): def __init__(self, dictionary, **kwargs): # ๐Ÿ‘‡๏ธ {'name': 'bobbyhadz', 'salary': 50, 'language': 'Python'} print(dictionary) # ๐Ÿ‘‡๏ธ {'tasks': ['develop', 'test'], 'age': 30} print(kwargs) for key, value in dictionary.items(): setattr(self, key, value) for key, value in kwargs.items(): setattr(self, key, value) my_dict = {'name': 'bobbyhadz', 'salary': 50, 'language': 'Python'} bob = Developer(my_dict, tasks=['develop', 'test'], age=30) print(bob.name) # ๐Ÿ‘‰๏ธ bobbyhadz print(bob.tasks) # ๐Ÿ‘‰๏ธ ['develop', 'test']

taking keyword arguments when creating an instance

The code for this article is available on GitHub

The class's __init__() method optionally takes keyword arguments after the dictionary.

However, you are not required to pass keyword arguments if you don't have any.

# Replacing spaces in dictionary keys with underscores

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

main.py
class Developer(): def __init__(self, dictionary): for key, value in dictionary.items(): setattr(self, str(key).replace(' ', '_'), value) my_dict = {'first name': 'bobbyhadz', 'salary': 50, 'language': 'Python'} bob = Developer(my_dict) print(bob.first_name) # ๐Ÿ‘‰๏ธ bobbyhadz print(bob.salary) # ๐Ÿ‘‰๏ธ 50 print(bob.language) # ๐Ÿ‘‰๏ธ Python
The code for this article is available on GitHub

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.

# Initializing attributes to None

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

main.py
class Developer(): 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 = {'first name': 'bobbyhadz', 'salary': 50, 'language': 'Python'} bob = Developer(my_dict) print(bob.name) # ๐Ÿ‘‰๏ธ bobbyhadz print(bob.salary) # ๐Ÿ‘‰๏ธ 50 print(bob.language) # ๐Ÿ‘‰๏ธ Python
The code for this article is available on GitHub

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

# Creating class instances from a Dictionary using unpacking

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 Developer(): def __init__(self, name, salary, language): self.name = name self.salary = salary self.language = language my_dict = {'name': 'bobbyhadz', 'salary': 50, 'language': 'Python'} bob = Developer(**my_dict) print(bob.name) # ๐Ÿ‘‰๏ธ bobbyhadz print(bob.salary) # ๐Ÿ‘‰๏ธ 50 print(bob.language) # ๐Ÿ‘‰๏ธ Python
The code for this article is available on GitHub

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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev