Turning @Tomerikoo's comment into an answer:

Use a list comprehension:

[o.name for o in l]

Note that this will not necessarily be more efficient than looping, but obviously more beautiful.

Answer from arne on Stack Overflow
Discussions

How to get field value from array of objects in python? - Stack Overflow
My task is to check if there is ... segments array and if rubric id is some other special value. But something is wrong in my filtration and I always get empty filtered_data and I can't understand why. It's my first attempt to write python code, please don't be so strict. ... def get_data_from_json(self, ... More on stackoverflow.com
🌐 stackoverflow.com
python - Get array of a specific attribute of all objects from an array of objects - Stack Overflow
I have an array containing a set of an object with many attributes. I want to get the values of specific attributes as a list in a simple way. I do know that I can make a list of each attribute an... More on stackoverflow.com
🌐 stackoverflow.com
Searching Array of Data Objects
I have a data object defined: @dataclass class Blower: id_: str name: str off: bool As I create objects I place then into an array: blwr=Blower( ) blowers.append(blwr) Now I want to search ‘blowers’ for an object with a certain ‘id_’ value. I can’t seem to find how to do that. More on discuss.python.org
🌐 discuss.python.org
3
0
May 22, 2020
get array values in python - Stack Overflow
I have the values arr1 as 25,26 and arr2 values as A,B Its always that the number of values in arr1 and arr2 are equal My question is that for i in arr1.split(","): pr... More on stackoverflow.com
🌐 stackoverflow.com
June 2, 2011
🌐
W3Schools
w3schools.com › python › python_arrays.asp
Python Arrays
An array can hold many values under a single name, and you can access the values by referring to an index number. You refer to an array element by referring to the index number. ... Use the len() method to return the length of an array (the ...
Top answer
1 of 2
2

One strategy to identify bugs in this code is to remove all conditions in the if clause, then add them one by one and checking whether the result is as expected.

You use the function hasattr. This function checks whether an object has a specific attribute (member variable, e.g., data[0].segments). data[0], however, is a dict. Dicts don't have a member called segments. What you're looking for is whether the dict contains a key segments, which you can achieve with the in operator:

if "segments" in item:
    ...

Then, there's another issue in your code. item["segments"] is a list, so you must use integers to access its members. Therefore, you get the error

TypeError: list indices must be integers or slices, not str

This error points towards the statement seg_id in item["segments"]["id"]. You can solve this with a double for loop or set comprehension and set intersection:

set(filter_config["segment_ids"]) & {seg["id"] for seg in item["segments"]}

Sets are containers wherein each element is unique. The operator & computes the intersection of two sets, i.e., the set of elements that are in both sets. set(filter_config["segment_ids"]) converts your list of segment IDs (I assume, it's a list) into a set. The set comprehension {seg["id"] for seg in item["segments"]} creates a set containing each segment IDs from the segments in the current item. The set is evaluated as true in an if statement iff the set is not empty.

Then, you should get your desired result.

Again, when you have a complex expression that doesn't work as expected, try to break it down to simpler expressions and check whether they do what you expect. Especially when learning, you can use an interactive Python session to build complex commands step by step, e.g., adding more and more filters, until you get what you need.

2 of 2
1

If you write your code as a sequence of loops you'll find it easier to read and debug. Complex list comprehensions such as the one in your question serve no purpose other than to be unnecessarily esoteric and hard to debug and maintain.

You could consider using a generator to identify the dictionaries you're interested in.

Something like this:

import json
from collections.abc import Iterator

filter_config = {
    "segment_ids": {"22222222", "1010101"},
    "rubric_ids": {"345", "999", '123'}
}

# this will yield a dictionary if ANY of the "segments" "id" values are in the specified set
# and if the "rubric" "id" is in its set
def gen_valid_dictionaries(data: list[dict]) -> Iterator[dict]:
    for d in data:
        for s in d.get("segments", []):
            if s.get("id") in filter_config["segment_ids"]:
                id_ = d.get("rubric", {}).get("id")
                if id_ in filter_config["rubric_ids"]:
                    yield d
                    break

with open("foo.json") as f:
    data = json.load(f)
    filtered_data = [d for d in gen_valid_dictionaries(data)]
Top answer
1 of 3
1

I would probably use the getattr built-in function for this purpose.

>>> my_object.my_attribute = 5
>>> getattr(my_object, 'my_attribute')
5

To create the numpy array as you would want:

def get_attrs(obj, attributes):
    """Returns the requested attributes of an object as a separate list"""
    return [getattr(obj, attr) for attr in attributes]

attributes = ['a', 'b', 'c']
attributes_per_object = np.array([get_attrs(obj, attributes) for obj in all_objects])
2 of 3
1

This answer is inspired from the answer of @energya using the getattr built-in function. As that answer makes a function to get a list of attributes of a specific object, while the question was for getting a list of one specific attribute for all the objects in the array of objects.

So using getattr function,

>>> my_object.my_attribute = 5
>>> getattr(my_object, 'my_attribute')
5

For getting a numpy array of a specific attribute of all objects:

def get_attrs(all_objects, attribute, args=None): 
    """Returns the requested attribute of all the objects as a list"""
    if(args==None):
        # If the requested attribute is a variable
        return np.array([getattr(obj, attribute) for obj in all_objects])
    else:
        # If the requested attribute is a method
        return np.array([getattr(obj, attribute)(*args) for obj in all_objects])

# For getting a variable 'my_object.a' of all objects
attribute_list = get_attrs(all_objects, attribute)

# For getting a method 'my_object.func(*args)' of all objects
attribute_list = get_attrs(all_objects, attribute, args)
🌐
GeeksforGeeks
geeksforgeeks.org › python › find-element-in-array-python
Find element in Array - Python - GeeksforGeeks
July 23, 2025 - Finding an item in an array in Python can be done using several different methods depending on the situation. Here are a few of the most common ways to find an item in a Python array.
🌐
Python.org
discuss.python.org › python help
Searching Array of Data Objects - Python Help - Discussions on Python.org
May 22, 2020 - I have a data object defined: @dataclass class Blower: id_: str name: str off: bool As I create objects I place then into an array: blwr=Blower(<blah blah>) blowers.append(blwr) Now I want to search ‘blow…
Find elsewhere
🌐
YouTube
youtube.com › watch
Python basics - Accessing a value in an array (or list!) - YouTube
This video will explain how to access a single value within an array. This is aimed at GCSE students so I treat python lists as if they are arrays. This will...
Published   July 31, 2020
🌐
C# Corner
c-sharpcorner.com › blogs › get-count-of-distinct-property-value-from-an-array-of-object-in-python2
Get Count of Distinct Property Value from an Array of Object in Python
July 28, 2023 - from collections import Counter ... property values and their counts for value, count in property_counts.items(): print(f"{value}: {count}")...
🌐
Data Science for Everyone
matthew-brett.github.io › cfd2020 › arrays › array_indexing.html
Selecting values from an array — Coding for Data - 2020 edition
We now have the names of the disciplines with the largest number of professors. ... array(['English', 'Mathematics', 'Biology', 'Psychology', 'History', 'Chemistry', 'Communications', 'Business'], dtype=object) Here we get the first value.
🌐
Educative
educative.io › answers › how-to-access-elements-from-an-array-in-python
How to access elements from an array in Python
Beside the array is the index [] operator, which will have the value of the particular element’s index position from a given array. Note that the value you pass into the index operator (the index position of the element you wish to access) must be an integer. ... It is worth noting that in Python, the first character of a list, string, array etc., is of index 0.
🌐
Bobby Hadz
bobbyhadz.com › blog › python-find-object-in-list-of-objects
Find object(s) in a List of objects in Python | bobbyhadz
If you only want to get the value of a specific attribute of the matching objects, return it from the list comprehension.
🌐
Tutorialspoint
tutorialspoint.com › python › python_access_array_items.htm
Python - Access Array Items
The enumerate() function can be used to access elements of an array. It accepts an array and an optional starting index as parameter values and returns the array items by iterating.
🌐
Python.org
discuss.python.org › python help
Instantatating an array of objects - Python Help - Discussions on Python.org
July 12, 2022 - Hello Everyone ! Actually I was instantating a array of objects like that : covergroup_names = [x for x in dir(coverage_points) if isclass(getattr(coverage_points, x))] covergroup_insts = [globals()[groupname](uut) for groupname in covergroup_names] And now the thing is that I added a method within the class called instant that instantiates if it’s not instatiated yet.
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.ndarray.item.html
numpy.ndarray.item — NumPy v2.5 Manual
This can be useful for speeding up access to elements of the array and doing arithmetic on elements of the array using Python’s optimized math. ... Try it in your browser! >>> import numpy as np >>> np.random.seed(123) >>> x = np.random.randint(9, size=(3, 3)) >>> x array([[2, 2, 6], [1, 3, 6], [1, 0, 1]]) >>> x.item(3) 1 >>> x.item(7) 0 >>> x.item((0, 1)) 2 >>> x.item((2, 2)) 1 · For an array with object dtype, elements are returned as-is.