使用Python排序JSON [英] Sort a JSON using Python

查看:125
本文介绍了使用Python排序JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Python JSON 对象进行排序.

I am trying ot sort a JSON Object using Python.

我有以下对象:

{ 
  "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}
   ]
}

我想改为拥有该对象:

{ 
  "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.

我已经尝试过此命令:

sorted_obj = sorted(json_obj['predictions'], key=lambda k: k['percentage'], reverse=True)

我有这个错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string indices must be integers

需要任何帮助

谢谢

推荐答案

您可以使用sorted对值进行排序,如下所示:

You can use sorted to sort the values, something like this :

json_obj = { 
  "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}
   ]
}

sorted_obj = dict(json_obj) 
sorted_obj['predictions'] = sorted(json_obj['predictions'], key=lambda x : x['percentage'], reverse=True)

print(sorted_obj)
print(json_obj)

这将导致:

# The sorted values based on 'predictions' -> 'percentage'
{'predictions': [{'percentage': 74.68, 'class': 'Class 2'}, {'percentage': 9.38, 'class': 'Class 3'}, {'percentage': 5.78, 'class': 'Class 4'}, {'percentage': 5.53, 'class': 'Class 5'}, {'percentage': 4.63, 'class': 'Class 1'}], 'text': 'hello world'}

# The original json_obj will remain unchanged as we have created a new object sorted_obj from values of json_obj using dict()
{'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}]}

这篇关于使用Python排序JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆