# 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
Labels:
dictionary,
filter,
filter list of dictionaries,
list,
python
Tuesday, May 19, 2020
How to sort a list of dictionaries in python
# This is a list of dictionaries in python
list_of_dictionaries = [{'id':2, "name":"python"}, {'id':1, "name":"import"}]
# This is the list, sorted by the key "name"
sortedlist = sorted(list_of_dictionaries, key=lambda k: k['name'])
# This is the list, reverse sorted by the key "name"
sortedlist = sorted(list_of_dictionaries, key=lambda k: k['name'], reverse=True)
#shortcut to learn more about the sorted function
# https://docs.python.org/3/howto/sorting.html
#understanding what lambda means
# https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions
Labels:
dictionaries,
dictionary,
list,
python,
sort,
sort list of dictionaries
Subscribe to:
Comments (Atom)