Python: how to sort a dicts array by two fields?

I'm a little new to Python ...

I have a dicts array that I received while 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 contains, among other things, three fields: "date" and "type" and "location". I need to sort the array first by date, then by type inside each block of identical dates, then by location in each block of the same types. How can i do this? thanks a lot!

+5
source share
1 answer
ws.sort(key=lambda datum: (datum['date'], datum['type'], datum['location']))

Tuples are sorted naturally, first using the first element, then using the following elements.

+9
source

All Articles