Python Sorted and Sort, Part 2
A quick look at the key parameter
Last week I did a quick study on the Python method list.sort() and built-in Python function sorted(). A quick recap from last week:
- Sort() is used only on lists
- Sort() modifies the list in-place
- Sorted() can be used on tuples, lists, sets, and dictionaries
- The sorted() function returns a sorted object from an iterable with no modification to the original
- Both have key and reverse as optional parameters
I’ll be using my coffee data frame again. It’s a data frame I scraped, cleaned, used to create GeoPandas visualizations, and performed classification modeling. My coffee_reviews_cleaned.csv data frame has 2,195 rows of coffee data and 19 feature columns.
Step one of this study of the key parameter is to create a list of dictionaries from the data frame:
coffee_list = df.to_dict(orient=’records’)
The result looks like this (only much longer given that there are 2,195 dictionaries!):
The plan is to order the list (of dictionaries) according to ‘Coffee Country’ and use the key parameter with the sorted function. The key parameter is a single argument function that will customize the list and is constructed by using lambda. Lambda is the anonymous function followed by the parameter name then the single block of code. The parameter list and code block are delineated by a colon. The syntax of lambda is:
lambda argument: expression
And the Python code is:
sorted(coffee_list, key = lambda country:country[‘Coffee Country’])
Which returns a list of dictionaries sorted alphabetically by country. Here is a partial result (and notice that the first two dictionaries in the list are from Bolivia):
Recall that coffee_list is a list (of dictionaries) and as such the sort method will work on this too, with even the same key expression!
coffee_list.sort(key = lambda country:country[‘Coffee Country’])
But, as you guessed, now the coffee_list is modified as a result of using sort().