Tip: Sorting an Array of Objects #39
kellyjonbrazil
started this conversation in
Show and tell
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Python has great sorting capabilities, but sometimes it's not obvious how to do it. For example, many APIs will present their data as a JSON array of objects. Something like:
In Jello, this will be presented as a list of dictionaries. More accurately, it will be a list of
DotMap
objects which behave just like dictionaries except they allow using dot notation.To sort this data, we need to decide which field to sort on and decide which method we would like to use. In either case, we will be using the Python builtin
sorted()
function and let's sort by thebar
key.Method 1 (
lambda
)Method 2 (
itemgetter
)Both of these methods successfully sort the data by the desired key and provide the following output:
The
sorted()
function also supports thereverse=[True|False]
argument to sort descending vs. ascending order.Beta Was this translation helpful? Give feedback.
All reactions