Let's say we have a list of objects like this:
my_objects = [
{
"id":0,
"some_value":"a"
},
{
"id":1,
"some_value":"a"
},
{
"id":2,
"some_value":"b"
},
{
"id":3,
"some_value":"b"
},
]
Given a list of ids like this:
ids = [1, 2]
What would be a pythonic way to retrieve a list of all the objects with the ids in this list? e.g.:
my_objects_filtered = [
{
"id":1,
"some_value":"a"
},
{
"id":2,
"some_value":"b"
}
]
What I want in the end is a list of the "some_value" value for all ids in the list "ids":
ids = [a, b]
Which I could get by doing this:
some_values = [my_object.param_id for my_object in my_objects_filtered]
But I do not know how to get my_objects_filtered
Thanks in advance.
Something like the below
my_objects = [
{
"id": 0,
"some_value": "a"
},
{
"id": 1,
"some_value": "a"
},
{
"id": 2,
"some_value": "b"
},
{
"id": 3,
"some_value": "b"
},
]
ids = [1, 2]
final_list = [x['some_value'] for x in my_objects if x['id'] in ids]
print(final_list)
output
['a', 'b']