-1

folks! I have a list of lists (actually, imported from PostgreSQL as JSON) that looks like this:

[{'person_name': 'FRAUDSTER_3', 'score': 10.33}, {'person_name': 'FRAUDSTER_5', 'score': 10.11}, {'person_name': 'FRAUDSTER_2', 'score': 10.44}, {'person_name': 'FRAUDSTER_4', 'score': 10.22}, {'person_name': 'FRAUDSTER_1', 'score': 10.55}]

Is there is a neat way to sort it by 'score' value using list.sort or sorted? Probably, lowest score first so I can use pop to get N records with maximum score first.

e-pirate
  • 153
  • 1
  • 10

2 Answers2

2

First of all, what you have is a list of dictionaries. You can then use operator.itemgetter to sort it:

In [362]: L = [{'person_name': 'FRAUDSTER_3', 'score': 10.33}, {'person_name': 'FRAUDSTER_5', 'score': 10.11}, {'person_name': 'FRAUDSTER_2', 'score': 10.44}, {'person_name': 'FRAUDSTER_4', 'score': 10.22}, {'person_name': 'FRAUDSTER_1', 'score': 10.55}]

In [363]: L.sort(key=operator.itemgetter('score'))

In [364]: [i['score'] for i in L]
Out[364]: [10.11, 10.22, 10.33, 10.44, 10.55]
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
1
sorted(yourlist, key=lambda x:x['score'])
Muposat
  • 1,476
  • 1
  • 11
  • 24
  • 1
    That's not how you access mappings in a dictionary. You mean `key=lambda x: x['score']` Default sort order is small -> large – Patrick Haugh Oct 18 '16 at 13:50
  • @Patrick Haugh, @Muposat: This is what I was searching for! `scoredict = sorted(scoredict, key=lambda x: x['score'])` and then `print(scoredict.pop())` as many times, as I need. Thanks, folks! – e-pirate Oct 18 '16 at 14:14
  • Answer corrected, thank you @Patrick Haugh – Muposat Oct 18 '16 at 14:42