Home > Software engineering >  Search for a dictionary based on a property value
Search for a dictionary based on a property value

Time:01-24

I am trying to get list of dictionaries from a list based on a specific property list of values? Any suggestions

list_of_persons = [
    {"id": 2, "name": "name_2", "age": 23},
    {"id": 3, "name": "name_3", "age": 43},
    {"id": 4, "name": "name_4", "age": 35},
    {"id": 5, "name": "name_5", "age": 59}
]

ids_search_list = [2, 4]

I'd like to get the following list

result_list = [
    {"id": 2, "name": "name_2", "age": 23},
    {"id": 4, "name": "name_4", "age": 35}
]

looping could be the simplest solution but there should be a better one in python

CodePudding user response:

you can do this like that :

list_of_persons = [
    {"id": 2, "name": "name_2", "age": 23},
    {"id": 3, "name": "name_3", "age": 43},
    {"id": 4, "name": "name_4", "age": 35},
    {"id": 5, "name": "name_5", "age": 59}
]

ids_search_list = [2, 4]
result = []

for person in list_of_persons:
    if person["id"] in ids_search_list:
        result.append(person)
        
print(result)

CodePudding user response:

You can use list comprehension

result_list = [person for person in list_of_persons if person["id"] in ids_search_list]

If you want some reading material about it: https://realpython.com/list-comprehension-python/

  • Related