How to filter list of dictionaries by certain Keys?

Question:

I have the following list:

list = [{'Jim': {'age': 20, 'lastname': 'Smith'}}, {'Sarah': {'age': 25, 'lastname': 'Jones'}}, {'Bill': {'age': 30, 'lastname': 'Lee'}}] 

I want to be able to filter list by Key, so for example if i want the the Sarah dict, i want the output to be that dictionary. for example:

output = {'Sarah': {'age': 25, 'lastname': 'Jones'}}
Asked By: loganengineer

||

Answers:

There is the filter function in python to do this :

my_list = = [{'Jim': {'age': 20, 'lastname': 'Smith'}}, {'Sarah': {'age': 25, 'lastname': 'Jones'}}, {'Bill': {'age': 30, 'lastname': 'Lee'}}]

filtered_list = filter(lambda x: 'Sarah' in x, my_list)

The first parameter is a function itself that take as argument each element of the list and return a boolean saying if the element should be kept.

Answered By: Xiidref

we can use a for loop to iterate over the list. doing so, we get a dictionary in each loop iteration. with the membership operator in we can check for the presence of the name.

lst = [{'Jim': {'age': 20, 'lastname': 'Smith'}}, {'Sarah': {'age': 25, 'lastname': 'Jones'}}, {'Bill': {'age': 30, 'lastname': 'Lee'}}] 
search = "Sarah"
for outer_dict in lst:
    if search in outer_dict:
        print(outer_dict)

output is: {'Sarah': {'age': 25, 'lastname': 'Jones'}}

Answered By: lroth
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.