Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an array of dictionaries from a Python list

I want to turn a list of interspersed values into an array of dictionaries.

I'm trying to make a list of prediction values in Python capable to be used with a JSON API. Once I have the dictionary, I'll use json.dumps on it.

my_list = [35, 2.75, 67, 3.45] # in form of: (value, score, value, score)

Ideal outcome:

my_array_of_dicts = [{'value':35, 'score':2.75}, {'value':67 'score':3.45}]

Here's what I've tried.

First attempt:

d = dict(zip(my_list[::2], my_list[1::2]))

And it produces...

> {35: 2.75,
   67: 3.45}

I'm not sure how to get custom keys. Or have each pair as its own dictionary.

Second attempt:

[{'value':i, 'score':i} for i in my_list]]

> [{'value':35, 'score':35}, {'value':2.75, 'score':2.75}, 
   {'value':67, 'score':67}, {'value':3.45, 'score':3.45}] 

It's close but it doesn't account for every second value being a score.

like image 689
Daniel Bourke Avatar asked Jan 08 '19 01:01

Daniel Bourke


2 Answers

You're really close with the zip version. You just need to make the object and specify the keys.

my_list = [35, 2.75, 67, 3.45] 

[{'value': v, 'score': s} for v, s in zip(my_list[::2], my_list[1::2])]

result:

[{'value': 35, 'score': 2.75}, {'value': 67, 'score': 3.45}]
like image 68
Mark Avatar answered Sep 22 '22 20:09

Mark


In your second attempt, do score: i + 1. In the loop do for i in range(0, len(my_list), 2).

like image 34
Andrew Ray Avatar answered Sep 24 '22 20:09

Andrew Ray