Iterate over an Object's attributes in Python

avatar
Borislav Hadzhiev

Last updated: Apr 10, 2024
4 min

banner

# Table of Contents

  1. Iterate over an Object's attributes in Python
  2. Iterate over an Object's attributes using vars()
  3. Iterate over an Object's attributes using dir()
  4. Exclude the attributes that start with two underscores when iterating
  5. Exclude the methods when iterating over the object
  6. Iterating only over the class's variables

# Iterate over an Object's attributes in Python

To iterate over an object's attributes:

  1. Use the __dict__ attribute to get a dictionary containing the object's properties and values.
  2. Use the dict.items() method to get a view of the dictionary's items.
  3. Use a for loop to iterate over the object's attributes.
main.py
class Employee(): cls_id = 'employee' def __init__(self, name, salary): self.name = name self.salary = salary emp1 = Employee('bobbyhadz', 100) for attribute, value in emp1.__dict__.items(): # name bobbyhadz # salary 100 print(attribute, value)

iterate over object attributes

The code for this article is available on GitHub

The example uses the __dict__ attribute to get a dictionary containing the object's properties and values.

main.py
class Employee(): cls_id = 'employee' def __init__(self, name, salary): self.name = name self.salary = salary emp1 = Employee('bobbyhadz', 100) # ๐Ÿ‘‡๏ธ {'name': 'bobbyhadz', 'salary': 100} print(emp1.__dict__)

We can use the dict.items() method to get a view object we can iterate over.

main.py
class Employee(): cls_id = 'employee' def __init__(self, name, salary): self.name = name self.salary = salary emp1 = Employee('bobbyhadz', 100) for attribute, value in emp1.__dict__.items(): # name bobbyhadz # salary 100 print(attribute, value)

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

The last step is to use a for loop to iterate over the object's attributes.

# Iterate over an Object's attributes using vars()

An alternative to using the __dict__ attribute is to use the built-in vars() function.

main.py
class Employee(): cls_id = 'employee' def __init__(self, name, salary): self.name = name self.salary = salary emp1 = Employee('bobbyhadz', 100) for attribute, value in vars(emp1).items(): # name bobbyhadz # salary 100 print(attribute, value)

iterate over object attributes using vars

The code for this article is available on GitHub

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.

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

# Iterate over an Object's attributes using dir()

This is a three-step process:

  1. Use the dir() function to get a list of the names of the object's attributes.
  2. Optionally filter out attributes that start with two underscores and methods.
  3. Use a for loop to iterate over the object's attributes.
main.py
class Employee(): cls_id = 'employee' def __init__(self, name, salary): self.name = name self.salary = salary emp1 = Employee('bobbyhadz', 100) for attribute in dir(emp1): print(attribute, getattr(emp1, attribute)) result = [attribute for attribute in dir(emp1) if not attribute.startswith('__')] print(result) # ๐Ÿ‘‰๏ธ ['cls_id', 'name', 'salary']
The code for this article is available on GitHub

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, name, salary): self.name = name self.salary = salary emp1 = Employee('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', 'name', 'salary'] print(dir(emp1))

You can also pass a class to the dir() function, it doesn't just accept instances.

# Exclude the attributes that start with two underscores when iterating

If you need to exclude the attributes that start with two underscores, use a list comprehension.

main.py
class Employee(): cls_id = 'employee' def __init__(self, name, salary): self.name = name self.salary = salary emp1 = Employee('bobbyhadz', 100) attributes = [attribute for attribute in dir(emp1) if not attribute.startswith('__')] print(attributes) # ๐Ÿ‘‰๏ธ ['cls_id', 'name', 'salary'] for attr in attributes: # cls_id employee # name bobbyhadz # salary 100 print(attr, getattr(emp1, attr))

exclude attributes that start with two underscores

The code for this article is available on GitHub
You can use the getattr() function if you need to get the value of an attribute when given the attributes name as a string.

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

The function takes the following parameters:

NameDescription
objectthe object whose attribute should be retrieved
namethe name of the attribute
defaulta default value for when the attribute doesn't exist on the object

# Exclude the methods when iterating over the object

If your class has methods, you might also want to exclude the methods when iterating over the object's attributes.

main.py
class Employee(): cls_id = 'employee' def __init__(self, name, salary): self.name = name self.salary = salary def get_name(self): return self.name emp1 = Employee('bobbyhadz', 100) attributes = [attribute for attribute in dir(emp1) if not attribute.startswith('__') and not callable(getattr(emp1, attribute))] print(attributes) # ๐Ÿ‘‰๏ธ ['cls_id', 'name', 'salary'] for attr in attributes: # cls_id employee # name bobbyhadz # salary 100 print(attr, getattr(emp1, attr))
The code for this article is available on GitHub

The callable function takes an object as an argument and returns True if the object appears callable, otherwise False is returned.

We used the function to exclude all methods from the attributes.

# Iterating only over the class's variables

If you only want to iterate over the class's variables, you will pass the class to the dir() function, not the instance.

main.py
class Employee(): cls_id = 'employee' another = 'foo' def __init__(self, name, salary): self.name = name self.salary = salary class_variables = [attribute for attribute in dir(Employee) if not attribute.startswith('__') and not callable(getattr(Employee, attribute)) ] print(class_variables) # ๐Ÿ‘‰๏ธ ['another', 'cls_id'] for attr in class_variables: # another foo # cls_id employee print(attr, getattr(Employee, attr))
The code for this article is available on GitHub

We passed the class to the dir() function and filtered out all class variables that start with two underscores and all class methods before iterating.

# 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