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.

Dave
  • 15,639
  • 133
  • 442
  • 830

2 Answers2

4

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)
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
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.

m_____z
  • 1,521
  • 13
  • 22