Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add multiple comparisons in if else python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading