Split list values inside dictionary to separate dictionaries

五迷三道 提交于 2021-01-27 20:11:25

问题


I have the following json response from a flask application and am wondering how I can split it out into multiple "rows"/dicts.

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)}

回答1:


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:

[{'class': 0.0, 'probability': 0.8488858872836712}, {'class': 1.0, 'probability': 0.1511141127163287}]



回答2:


Assuming the output stored in d, you can do

[{'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}]
>>> 



回答3:


Split json using list comprehension

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:-

[{'class': 0.0, 'probability': 0.8488858872836712}, {'class': 1.0, 'probability': 0.1511141127163287}]


来源:https://stackoverflow.com/questions/58703305/split-list-values-inside-dictionary-to-separate-dictionaries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!