1

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.

2 Answers 2

5

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)
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.