5

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!

I Z
  • 5,719
  • 19
  • 53
  • 100
  • Try this: http://stackoverflow.com/questions/1143671/python-sorting-list-of-dictionaries-by-multiple-keys/1144405#1144405 – hughdbrown Mar 06 '13 at 22:14
  • Although it's not needed here, it's nice to know that python's sort [is stable](http://wiki.python.org/moin/HowTo/Sorting/#Sort_Stability_and_Complex_Sorts). – Lauritz V. Thaulow Mar 06 '13 at 22:17

1 Answers1

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

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

Pavel Anossov
  • 60,842
  • 14
  • 151
  • 124