Python sorted method treats a two-character string as a three-character string

I am using python 2.7.6 and I have a problem sorting a json object using sorted (as a list of dictionaries).

When I first looked at the sorted output, it seems that the list was only partially sorted, as there was less in between. Upon closer inspection, it turns out that two digits such as 93 were handled as 93X. With this understanding, the sorted result then turned out to be correct.

Not sure why this is happening. At first I thought it might be because I had not converted the json object to python object properly before sorting. However, I doubt this is a problem, since the json.load in the code is deserializing the json object into a python object.

Here's the jsbin of the "sorted" output. I tried to re-sort the sorted list and it gives me the same result.

Code below:

import json

json_data = open('test.json')
data = json.load(json_data)

results = sorted(data, key = lambda item : item["AveragePoints"], reverse = True)

with open('output.json', 'w') as outfile:
    json.dump(results, outfile);

json_data.close()

      

+3


source to share


1 answer


Before sorting, you need to convert AveragePoints

to a number like

sorted(data, key = lambda item : float(item["AveragePoints"]), reverse = True)

      



The values AveragePoints

will now compare as floats, so the sort will be correct.

Note. ... If you are sure it AveragePoints

will always be an integer, you can use a function int

instead float

.

+3


source







All Articles