How do I fix this sorting error?

81 Views Asked by At

I currently have the code below but for some reason it only sorts using the first number from the array so for example if the number was 1000 and it was compared to a 50 the 50 would be greater then the 1000. How do i fix this?

#!/usr/local/bin/python3.4
import operator
import pygame, sys
from pygame.locals import *
import random

placement = [1, 2, 3, 4, 5]
data = [
    {"score": "1000", "grade": "E", "music": "song5", "maxcombo": "1", "perfect": "20", "great": "1", "good": "20", "miss": "1"},
    {"score": "200", "grade": "D", "music": "song4", "maxcombo": "2", "perfect": "20", "great": "2", "good": "20", "miss": "2"},
    {"score": "500", "grade": "C", "music": "song3", "maxcombo": "3", "perfect": "20", "great": "3", "good": "20", "miss": "3"},
    {"score": "400", "grade": "B", "music": "song2", "maxcombo": "4", "perfect": "20", "great": "4", "good": "20", "miss": "4"},
    {"score": "300", "grade": "A", "music": "song1", "maxcombo": "5", "perfect": "20", "great": "5", "good": "20", "miss": "5"},
]

print (sorted(data, key=operator.itemgetter("score"), reverse=True))
1

There are 1 best solutions below

0
On

"1000" isn't a number. It's a string whose characters happen to be digits. If you want to sort numerically, represent your data with numbers.

data = [
    {"score": 1000, "grade": "E", "music": "song5", "maxcombo": 1, "perfect": 20, "great": 1, "good": 20, "miss": 1},
    #... etc

Or, if you have to keep them as strings for some reason, convert to integer in the key function.

print (sorted(data, key=lambda row: int(row["score"]), reverse=True))