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. Output: {'class': [0.0, 1.0], 'probability': [0.84
Solution 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}]
Solution 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 172019, 12:16:48)
[GCC 9.2.120190827 (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 inzip(d['class'], d['probability'])])
[{'class': 0.0, 'probability': 0.8488858872836712},
{'class': 1.0, 'probability': 0.1511141127163287}]
>>>
Solution 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 inzip(dic['class'],dic['probability'])]
print(split_value)
Output:-
[{'class': 0.0, 'probability': 0.8488858872836712}, {'class': 1.0, 'probability': 0.1511141127163287}]
Post a Comment for "Split List Values Inside Dictionary To Separate Dictionaries"