0

I've recently been using this code answered from another question:

foo = []
for line in test:
    x = line.split()
    y = int(x[1])
    foo.append({"Name":x[0],"Average":str(y)})
    print(x)
    sorted_x = sorted(foo)
    print sorted_x

I used this to sort averages. However, the code fails to sort averages producing results as such: [{'Average': '2.3333333333333335', 'Name': 'Alex'}] [{'Average': '1.0', 'Name': 'Harry'}] [{'Average': '9.0', 'Name': 'Lick'}]

As seen it's not sorted from highest to lowest or lowest to highest. How would I be able to change this code so it does sort from highest to lowest or vice verse?

Thanks

3
  • probably you should store numbers instead of strings? Commented Apr 5, 2016 at 14:59
  • 1
    Sort outside the for loop, no need to sort in each iteration. Plus do not convert average to str if you need to sort by average. Commented Apr 5, 2016 at 15:02
  • Consider that if you work on large list do not use insertion sort. On the other hand you can create your custom list which inherited from list. And when you add/remove item to the list you can sort it Commented Apr 5, 2016 at 15:09

2 Answers 2

2

sorted(foo, key=lambda x:x['Average'])

https://docs.python.org/3/library/functions.html#sorted

You may prefer foo.sort(lambda x:x['Average']) which returns None but sorts foo itself in-place

If you want to insert an element into a sorted list, import bisect

PS if print sorted_x isn't throwing a syntax error, you're on Python 2

Sign up to request clarification or add additional context in comments.

6 Comments

'sorted_x = sorted(foo, lambda x:x['Average']) TypeError: must use keyword argument for key function' I seem to be getting this error. Have I done something wrog?
It should be sorted(foo,key=lambda x:x['Average']).
My bad. I've updated my answer to use the explicit param. I assumed sorted would follow sort in not requiring one say 'key='. NB your average shouldn't be a string, as "12" < "2"
@alhal sorted_x = sorted(foo, key = lambda x:x['Average'])
sorted produces a new list, so it doesn't sort foo
|
1

Sorting a list after every update can be fine for small lists, but will be resource-consuming with long lists.

If you need to automatically maintain a sort order while updating a list, try SortedContainers.

2 Comments

This is no answer to his question.
The use of some kind of data structure that allows fast sorting while inserting, like the suggested SortedContainers, is the right answer to this question.

Your Answer

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