简体   繁体   中英

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM