# This is a list of dictionaries in python
list_of_dictionaries = [{'id':2, "name":"python"}, {'id':1, "name":"import"}, {'id':3, "name":"bye!"}]
# This is the list, filtered by the 'name' key
# returns a list that contains one element -- the dictionary with id == 1
filteredlist = list(filter(lambda d: d['name'] in ['import'], list_of_dictionaries))
# This is the list, filtered by the 'name' key
# returns a list that contains two dictionaries
filteredlist = list(filter(lambda d: d['name'] in ['import','python'], list_of_dictionaries))
# understanding the filter function
# https://docs.python.org/3/library/functions.html#filter
# understanding what lambda means
# https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions
Wednesday, May 27, 2020
How to filter a list of dictionaries in python
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment