Last updated: Apr 9, 2024
Reading timeยท3 min
To create class instances from a dictionary:
__init__()
method.setattr
method to assign each key-value pair as an instance
attribute.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).
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.
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.
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.
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
.
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 could 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.
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.
You can learn more about the related topics by checking out the following tutorials: