Reputation: 85
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)}
Upvotes: 2
Views: 1017
Reputation: 154
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}]
Upvotes: 1
Reputation: 71461
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}]
Upvotes: 3
Reputation: 5372
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}]
>>>
Upvotes: 1