0

I have a list of objects. Object has >10 attributes. I want to make a list containing only subsets of specific attributes from class.

Is there any built-in functions to do that? Or if not, what would be the most pythonic way to do this?

I tried this, but I would prefer to have a dynamic way to reference the specific attributes (e.g. pass a dictionary or a similar solution, that would enable me to figure out which attributes in runtime)

filtered_list = [[object.attr1, object.attr2] for object in list_objects]

(The solution can be just for Python 3)

MrT77
  • 811
  • 6
  • 25

2 Answers2

1

Something like

[[getattr(o, a) for a in ['attr1', 'attr2']] for o in objects]

should do it.

Ture Pålsson
  • 6,088
  • 2
  • 12
  • 15
1

If you want a list of dictionaries of object attributes:

# the list of attributes to get from each object
attrs = ['attr1', 'attr2']

# using dictionary comprehension to generate the list of attributes and their values
attr_vals_dict = [{a:getattr(o, a) for a in attrs} for o in objects]

Output:

[{'attr1': 1, 'attr2': 2}, {'attr1': 3, 'attr2': 4}, {'attr1': 'banana', 'attr2': 'apple'}]

As far as getting the dynamic list of attributes in the first place, that's already been answered here.

Random Davis
  • 6,662
  • 4
  • 14
  • 24