Skip to content Skip to sidebar Skip to footer

In Python, How Do I Sort An Array Of Json Objects By A Value In Each Object?

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 fig

Solution 1:

Use either a lambda function (with a parameter named json or whatever):

arr.sort(key = lambda json: json['score'], reverse=True)

Or, operator.itemgetter:

from operator import itemgetter

arr.sort(key = itemgetter('score'), reverse=True)

Solution 2:

You can use sorted(iterable, key) and itemgetter as follows:

>>> from operator import itemgetter
>>> arr = [{'score': 10, 'name': 'Bob'}, {'score': 15, 'name':'Susan'}, {'score': 1, 'name': 'Skippy'}]
>>> sorted(arr, key=itemgetter('score'), reverse=True)
[{'score': 15, 'name': 'Susan'}, {'score': 10, 'name': 'Bob'}, {'score': 1, 'name': 'Skippy'}]

itemgetter('score') allows sorted to access the key element in of each dictionary in your list of dictionaries and order the list accordingly.

Post a Comment for "In Python, How Do I Sort An Array Of Json Objects By A Value In Each Object?"