Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 906
I Z Avatar asked Mar 06 '13 21:03

I Z


People also ask

How do you sort a list with two conditions in Python?

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.

Can you sort a list of dictionaries in Python?

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.

How do I sort a list of dictionaries by key?

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.


1 Answers

ws.sort(key=lambda datum: (datum['date'], datum['type'], datum['location']))

Tuples are sorted naturally first by first element, then by succeeding elements.

like image 185
Pavel Anossov Avatar answered Sep 23 '22 19:09

Pavel Anossov