How do I search a list of dictionaries with multiple keys?

Viewed 130

Imagine I have the following list of dictionaries in Python:

[
    {"name": "John", "surname": "Doe", "age": 20},
    {"name": "Anna", "surname": "Smith", "age": 20},
    {"name": "John", "surname": "Doe", "age": 22},
]

So now I want for example all dictionaries, where 'name'=='John' and 'surname'=='Doe'; In this case, the output would be

[
    {"name": "John", "surname": "Doe", "age": 20},
    {"name": "John", "surname": "Doe", "age": 22},
]

I found plenty of examples on how to search a list of dictionary with 1 key but not for 2 or potentially 3 and more keys..

Many thanks

1 Answers

First, don't call a list, which is a built-in python type, such as "list".

Then:

lst = [{'name':'John', 'surname':'Doe','age':20},{'name':'Anna','surname':'Smith','age':20},{'name':'John','surname':'Doe','age':22}]


print([d for d in lst if d['name'] == 'John' and d['surname'] == 'Doe'])

Output:

[{'name': 'John', 'surname': 'Doe', 'age': 20}, {'name': 'John', 'surname': 'Doe', 'age': 22}]
Related