Home > Back-end >  How to filter list of dictionaries by certain Keys?
How to filter list of dictionaries by certain Keys?

Time:08-18

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'}}

CodePudding user response:

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.

CodePudding user response:

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'}}

  • Related