我从flask应用程序收到以下json响应,想知道如何将其拆分为多个“行” / dict。
输出:
{'class': [0.0, 1.0],
'probability': [0.8488858872836712, 0.1511141127163287]}
我想要的是:
[{"class": 0.0, "probability": 0.8488858872836712},{"class": 1.0, "probability": 0.1511141127163287}]
我尝试了以下操作,但不确定如何获取这两个密钥:
{k: v for e in zip(model.classes_, probabilities[0]) for k, v in zip(('class', 'probability'), e)}
答案 0 :(得分:1)
假设输出存储在d
中,您可以完成
[{'class': c, 'probability': p} for c,p in zip(d['class'], d['probability'])]
这将导致:
[{'class': 0.0, 'probability': 0.8488858872836712},
{'class': 1.0, 'probability': 0.1511141127163287}]
这里是概念证明:
Python 3.7.5 (default, Oct 17 2019, 12:16:48)
[GCC 9.2.1 20190827 (Red Hat 9.2.1-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from pprint import pprint
>>> d={'class': [0.0, 1.0],
... 'probability': [0.8488858872836712, 0.1511141127163287]}
>>> pprint([{'class': c, 'probability': p} for c,p in zip(d['class'], d['probability'])])
[{'class': 0.0, 'probability': 0.8488858872836712},
{'class': 1.0, 'probability': 0.1511141127163287}]
>>>
答案 1 :(得分:1)
更通用的解决方案(如果您不提前知道密钥名称):
implicit val orderer = Ordering.Double.TotalOrdering
myMap.toList.sortBy(_._2)
// res1: List[(String, Double)] = List((4,0.3), (2,2.1), (3,3.4), (1,4.6))
输出:
d = {'class': [0.0, 1.0], 'probability': [0.8488858872836712, 0.1511141127163287]}
result = [dict(zip(d.keys(), i)) for i in zip(*d.values())]
答案 2 :(得分:1)
使用列表推导拆分json
dic = { 'class': [0.0, 1.0], 'probability': [0.8488858872836712, 0.1511141127163287] }
split_value = [{'class':i,'probability':j} for i,j in zip(dic['class'],dic['probability'])]
print(split_value)
输出:-
[{'class': 0.0, 'probability': 0.8488858872836712}, {'class': 1.0, 'probability': 0.1511141127163287}]