Reputation: 19120
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)
but I can't figure out how to reference the JSON object from the "key" part of the sort function.
Upvotes: 1
Views: 7227
Reputation: 22776
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)
Upvotes: 4
Reputation: 1591
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.
Upvotes: 3