按值排序JSON数组 - Python

时间:2015-10-30 19:58:05

标签: python json list

我有一个看起来像这样的JSON数组

[{'age':1, 'name':'james'}, {'age':3, 'name':'henry'}, {'age':10, 'name':'andrew'}]

是否可以按照人们的年龄来订购,以便它像这样

[{'age':10, 'name':'andrew'}, {'age':3, 'name':'henry'}, {'age':1, 'name':'james'}]

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

In [13]: import json

In [14]: l = json.loads('[{"age": 1, "name": "james"}, {"age": 3, "name": "henry"}, {"age": 10, "name": "andrew"}]')

In [15]: json.dumps(sorted(l, key=lambda x: x["age"], reverse=True))
Out[15]: '[{"age": 10, "name": "andrew"}, {"age": 3, "name": "henry"}, {"age": 1, "name": "james"}]'