Set instance attributes from a Dictionary in Python

avatar

Borislav Hadzhiev

Last updated: Sep 16, 2022

banner

Photo from Unsplash

Set instance attributes from a Dictionary in Python #

To set instance attributes from a dictionary:

  1. Iterate over the dictionary's items in the class's __init__() method.
  2. Use the setattr method to set 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

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.

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']

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.

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 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 '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

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

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. Developer(name='bobbyhadz', salary=50, language='Python').

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.