I am trying ot sort a JSON Object using Python.
I have the following object :
{
"text": "hello world",
"predictions":
[
{"class": "Class 1", "percentage": 4.63},
{"class": "Class 2", "percentage": 74.68},
{"class": "Class 3", "percentage": 9.38},
{"class": "Class 4", "percentage": 5.78},
{"class": "Class 5", "percentage": 5.53}
]
}
And I want to have this object instead :
{
"text": "hello world",
"predictions":
[
{"class": "Class 2", "percentage": 74.68},
{"class": "Class 3", "percentage": 9.38},
{"class": "Class 4", "percentage": 5.78},
{"class": "Class 5", "percentage": 5.53},
{"class": "Class 1", "percentage": 4.63}
]
}
In fact, I want to order my array of objects by percentage.
I have tried this command :
sorted_obj = sorted(json_obj['predictions'], key=lambda k: k['percentage'], reverse=True)
And I had this error :
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string indices must be integers
Any help is needed,
Thanks
lists and JSON objects to Pythondicts.dicts are unordered in Python. You would need some ordered container. Try to store the data in anOrderedDict:from collections import OrderedDict