在Python中,如何按每个对象中的值对JSON对象数组进行排序? [英] In Python, how do I sort an array of JSON objects by a value in each object?
本文介绍了在Python中,如何按每个对象中的值对JSON对象数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Python 3.7.我有一个JSON对象数组.我想根据每个JOSN对象中的值之一(分数")对对象数组进行排序.我在弄清楚如何编写sort函数时遇到了麻烦.我尝试过了
I'm using Python 3.7. I have an array of JSON objects. I would like to sort the array of objects based on one of the values ("score") in each JOSN object. I'm having trouble figuring out how to write the sort function. I tried this
>>> arr = [{'score': 10, 'name': 'Bob'}, {'score': 15, 'name':'Susan'}, {'score': 1, 'name': 'Skippy'}]
>>> arr
[{'score': 10, 'name': 'Bob'}, {'score': 15, 'name': 'Susan'}, {'score': 1, 'name': 'Skippy'}]
>>> arr.sort(key=json['score'], reverse=True)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'json' is not defined
>>> arr.sort(key=json['score'], reverse=True)
但是我不知道如何从sort函数的键"部分引用JSON对象.
but I can't figure out how to reference the JSON object from the "key" part of the sort function.
推荐答案
使用 lambda
函数(带有名为 json
的参数或其他参数):
Use either a lambda
function (with a parameter named json
or whatever):
arr.sort(key = lambda json: json['score'], reverse=True)
或者, operator.itemgetter
:
from operator import itemgetter
arr.sort(key = itemgetter('score'), reverse=True)
这篇关于在Python中,如何按每个对象中的值对JSON对象数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文