Skip to content

Instantly share code, notes, and snippets.

@lightscalar
Last active January 6, 2025 13:22
Show Gist options
  • Save lightscalar/353243e41d34993f700a to your computer and use it in GitHub Desktop.
Save lightscalar/353243e41d34993f700a to your computer and use it in GitHub Desktop.
Iterating Over Object Attributes in Python

Given an object in Python, we can iterate over its attributes (much as we might iterate over keys in a dictionary) by using the following method. In this example, we convert an object into a list of the attribute contents of the object.

[data.__dict__[key] for key in data.__dict__.iterkeys()]

So, given a class,

class Example():

  def __init__():
    pass

We can create an instance and assign attributes:

ex = Example()
ex.a = 1
ex.b = 2
ex.c = 3

Then we find that:

contents = [ex.__dict__[key] for key in ex.__dict__.iterkeys()]
# --> contents = [1, 2, 3]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment