Wagish Srivastava Wagish Srivastava -4 years ago 88
Python Question

How to do 3 level of sorting in list of dictionary?

Here is the json which i wanted to sort in 3 level

eg: first sort remote_host then client_ip then timestamp and then make the output in a single json.

data = [{"timestamp": 1495126917.0, "client_ip": "10.200.3.55", "remote_host": "175.106.59.78"},
{"timestamp": 1495126915.0, "client_ip": "10.200.3.55", "remote_host": "175.106.59.78"},
{"timestamp": 1495126917.0, "client_ip": "10.200.3.55", "remote_host": "201.83.41.11"},
{"timestamp": 1495126913.0, "client_ip": "10.200.3.55", "remote_host": "78.47.139.58"},
{"timestamp": 1495126915.0, "client_ip": "10.200.3.55", "remote_host": "175.106.59.78"},
{"timestamp": 1495126917.0, "client_ip": "10.200.3.55", "remote_host": "201.83.41.11"},
{"timestamp": 1495126913.0, "client_ip": "10.200.3.55", "remote_host": "201.83.41.11"},
{"timestamp": 1495126915.0, "client_ip": "10.200.3.55", "remote_host": "78.47.139.58"},
{"timestamp": 1495126913.0, "client_ip": "10.200.3.55", "remote_host": "175.106.59.78"},
{"timestamp": 1495126915.0, "client_ip": "10.200.3.55", "remote_host": "201.83.41.11"}]

Answer Source
import json
import operator

data = [{"timestamp": 1495126917.0, "client_ip": "10.200.3.55", "remote_host": "175.106.59.78"}, {"timestamp": 1495126915.0, "client_ip": "10.200.3.55", "remote_host": "175.106.59.78"}, {"timestamp": 1495126917.0, "client_ip": "10.200.3.55", "remote_host": "201.83.41.11"}, {"timestamp": 1495126913.0, "client_ip": "10.200.3.55", "remote_host": "78.47.139.58"}, {"timestamp": 1495126915.0, "client_ip": "10.200.3.55", "remote_host": "175.106.59.78"}, {"timestamp": 1495126917.0, "client_ip": "10.200.3.55", "remote_host": "201.83.41.11"}, {"timestamp": 1495126913.0, "client_ip": "10.200.3.55", "remote_host": "201.83.41.11"}, {"timestamp": 1495126915.0, "client_ip": "10.200.3.55", "remote_host": "78.47.139.58"}, {"timestamp": 1495126913.0, "client_ip": "10.200.3.55", "remote_host": "175.106.59.78"}, {"timestamp": 1495126915.0, "client_ip": "10.200.3.55", "remote_host": "201.83.41.11"}]
print json.dumps(sorted(data, key=operator.itemgetter('remote_host', 'client_ip', 'timestamp')))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download