I am somewhat new to Python...
I have an array of dicts that I got by reading a file containing JSON messages, i.e. using something like this:
import json
ws = []
with open('messages.txt', 'r') as f:
for line in f:
data = json.loads(line)
ws.append(data)
Each JSON message has, among other things, three fields: "date" and "type" and "location". I need to sort the array first by date, then by type within each block of identical dates, then by location within each block of identical types. How can I do that? Thx much!
Use sorted() and a lambda expression to sort a list by two fields. Call sorted(a_list, key = k) with k as lambda x: x[i], x[j] to sort list by the i -th element and then by the j -th element.
We can sort lists, tuples, strings, and other iterable objects in python since they are all ordered objects. Well, as of python 3.7, dictionaries remember the order of items inserted as well. Thus we are also able to sort dictionaries using python's built-in sorted() function.
To sort a list of dictionaries according to the value of the specific key, specify the key parameter of the sort() method or the sorted() function. By specifying a function to be applied to each element of the list, it is sorted according to the result of that function.
ws.sort(key=lambda datum: (datum['date'], datum['type'], datum['location']))
Tuples are sorted naturally first by first element, then by succeeding elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With