I want to know if there is the way to do multiple comrapsions in if else without declaration in for loop
For example i have list of dict:
my_list = [
{
'first_name': 'Anna',
'last_name': 'Frank',
'id': 1
},
{
'first_name': 'Anna',
'last_name': 'New',
'id': 2
},
{
'first_name': 'Anna',
'last_name': 'Frank',
'id': 3
}
]
And i have request filters but i dont know exactly how many of them there will be and i want to filter this list of dict by my request filters
For example user will send me 2 filters: first_name and last_name
request is from Starlette
request_params = request.query_params
new_list = [data for data in my_list if user['first_name'] == 'something there']
user['first_name'] == 'something there' is just for example there
How to make filters in if without declare them in list comprehension and declare them maybe earlier
For example filter by first_name = Anna and last_name == Frank
I want to get this 2 filters or maybe more without every time passing and in if in list comprehension
>Solution :
If the user sends the filters as a dict, like this:
filters = {
'first_name': 'Anna',
'last_name': 'Frank',
}
Then you could check for matching entries like this:
matches = [data for data in my_list if all(data.get(key) == value for key, value in filters.items())]
UPDATE: Use data.get(key) instead of data[key] to allow for filter attributes that are missing from some data items