[英]Split list values inside dictionary to separate dictionaries
I have the following json response from a flask application and am wondering how I can split it out into multiple "rows"/dicts.我有来自 flask 应用程序的以下 json 响应,我想知道如何将其拆分为多个“行”/dicts。
Output: Output:
{'class': [0.0, 1.0],
'probability': [0.8488858872836712, 0.1511141127163287]}
What I desire is:我想要的是:
[{"class": 0.0, "probability": 0.8488858872836712},{"class": 1.0, "probability": 0.1511141127163287}]
I've tried something like the following but am not sure how to get both keys:我尝试过类似以下的方法,但不确定如何获取两个密钥:
{k: v for e in zip(model.classes_, probabilities[0]) for k, v in zip(('class', 'probability'), e)}
A more generic solution (if you do not know the key names ahead of time):更通用的解决方案(如果您提前不知道键名):
d = {'class': [0.0, 1.0], 'probability': [0.8488858872836712, 0.1511141127163287]}
result = [dict(zip(d.keys(), i)) for i in zip(*d.values())]
Output: Output:
[{'class': 0.0, 'probability': 0.8488858872836712}, {'class': 1.0, 'probability': 0.1511141127163287}]
Assuming the output stored in d
, you can do假设 output 存储在d
中,您可以这样做
[{'class': c, 'probability': p} for c,p in zip(d['class'], d['probability'])]
That will result in:这将导致:
[{'class': 0.0, 'probability': 0.8488858872836712},
{'class': 1.0, 'probability': 0.1511141127163287}]
Here is a proof of concept:这是一个概念证明:
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}]
>>>
Split json using list comprehension使用列表理解拆分 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)
Output:- Output:-
[{'class': 0.0, 'probability': 0.8488858872836712}, {'class': 1.0, 'probability': 0.1511141127163287}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.