Create a dictionary from an object in Python

avatar

Borislav Hadzhiev

Last updated: Sep 16, 2022

banner

Photo from Unsplash

Create a dictionary from an object in Python #

Use the __dict__ attribute to create a dictionary from an object, e.g. my_dict = my_obj.__dict__. The __dict__ attribute of an object returns a dictionary containing the object's properties and values.

main.py
class Employee(): cls_id = 'employee' def __init__(self, id, name, salary): self.id = id self.name = name self.salary = salary bob = Employee(1, 'bobbyhadz', 100) # ✅ create dictionary from an object (__dict__) my_dict = bob.__dict__ print(my_dict) # 👉️ {'id': 1, 'name': 'bobbyhadz', 'salary': 100} # ------------------------------------------------------------ # ✅ create dictionary from an object (vars()) my_dict = vars(bob) print(my_dict) # 👉️ {'id': 1, 'name': 'bobbyhadz', 'salary': 100} # ------------------------------------------------------------ # ✅ create dictionary from an object, including class variables my_dict = {key: getattr(bob, key) for key in dir(bob) if not key.startswith('__') and not callable(getattr(bob, key))} # 👇️ {'cls_id': 'employee', 'id': 1, 'name': 'bobbyhadz', 'salary': 100} print(my_dict)

We used the __dict__ attribute to create a dictionary from an object.

The __dict__ attribute returns a dictionary containing the object's properties and values.
main.py
class Employee(): # 👇️ class variable cls_id = 'employee' def __init__(self, id, name, salary): # 👇️ instance variable self.id = id self.name = name self.salary = salary bob = Employee(1, 'bobbyhadz', 100) # 👇️ {'id': 1, 'name': 'bobbyhadz', 'salary': 100} print(bob.__dict__)

Notice that the dictionary the __dict__ attribute returns doesn't contain the class variables.

Class variables are shared by all instances and can be accessed directly on the class, e.g. Employee.cls_id.

Instance variables are unique to each instance you create by instantiating the class.

Alternatively, you can use the vars() function.

Create a dictionary from an object using vars() #

Use the vars() function to create a dictionary from an object, e.g. my_dict = vars(object). The vars() function takes an object and returns a dictionary containing the object's properties and values.

main.py
class Employee(): cls_id = 'employee' def __init__(self, id, name, salary): self.id = id self.name = name self.salary = salary bob = Employee(1, 'bobbyhadz', 100) my_dict = vars(bob) print(my_dict) # 👉️ {'id': 1, 'name': 'bobbyhadz', 'salary': 100}

The vars function takes an object and returns the __dict__ attribute of the given module, class, instance or any other object that has a __dict__ attribute.

The vars() function raises a TypeError if the provided object doesn't have a __dict__ attribute.

Which approach you pick is a matter of personal preference. I'd use the __dict__ attribute directly to be more explicit.

If you need to include the class variables when creating the dictionary, use the dir() function.

Create a dictionary from an object using dir() #

To create a dictionary from an object:

  1. Use the dir() function to get a list of the names of the class's attributes.
  2. Use a dict comprehension to iterate over the list.
  3. Filter out the attributes that start with two underscores and the methods.
main.py
class Employee(): cls_id = 'employee' def __init__(self, id, name, salary): self.id = id self.name = name self.salary = salary bob = Employee(1, 'bobbyhadz', 100) my_dict = {key: getattr(bob, key) for key in dir(bob) if not key.startswith('__') and not callable(getattr(bob, key))} # 👇️ {'cls_id': 'employee', 'id': 1, 'name': 'bobbyhadz', 'salary': 100} print(my_dict)

The dir function returns a list of the names of the object's attributes, and recursively of the attribute of its base classes.

main.py
class Employee(): cls_id = 'employee' def __init__(self, id, name, salary): self.id = id self.name = name self.salary = salary bob = Employee(1, 'bobbyhadz', 100) # 👇️ ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'cls_id', 'id', 'name', 'salary'] print(dir(bob))

We now have to filter out all attributes that start with two underscores and all methods.

The remaining items are the names of the class and instance variables.

We used the str.startswith() method to exclude any attributes that start with two underscores.

We then used the callable() function to exclude any methods when converting to a dictionary.

main.py
class Employee(): cls_id = 'employee' def __init__(self, id, name, salary): self.id = id self.name = name self.salary = salary bob = Employee(1, 'bobbyhadz', 100) my_dict = {key: getattr(bob, key) for key in dir(bob) if not key.startswith('__') and not callable(getattr(bob, key))} # 👇️ {'cls_id': 'employee', 'id': 1, 'name': 'bobbyhadz', 'salary': 100} print(my_dict)

The getattr function returns the value of the provided attribute of the object.

The function takes the object, the name of the attribute and a default value for when the attribute doesn't exist on the object as parameters.

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.