1

i have the following dictionary of items in Python, but i want to sort the dictionary in order based on the value of a selected key. in this case score, i want the lowest number to be at the top so i can then select that item from the dictionary to be processed

[
  {
    "id": 1928430,
    "score": 0.5030304,
    "name": "John"
  },
  {
    "id": 7283849,
    "score": 0.2030304,
    "name": "Sam"
  },
  {
    "id": 8384954,
    "score": 0.3030304,
    "name": "Steven"
  }
]
  • There's definitely a good duplicate question with a great answer, but the short version is: `sorted(listodicts, key=operator.itemgetter('id'))` – abarnert Aug 16 '18 at 17:55

1 Answers1

1
l = [
  {
    "id": 1928430,
    "score": 0.5030304,
    "name": "John"
  },
  {
    "id": 7283849,
    "score": 0.2030304,
    "name": "Sam"
  },
  {
    "id": 8384954,
    "score": 0.3030304,
    "name": "Steven"
  }
]

print(sorted(l, key=lambda k: k['score']))

Output:

[{'id': 7283849, 'score': 0.2030304, 'name': 'Sam'}, {'id': 8384954, 'score': 0.3030304, 'name': 'Steven'}, {'id': 1928430, 'score': 0.5030304, 'name': 'John'}]
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40