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.
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}]
In your second attempt, do score: i + 1. In the loop do for i in range(0, len(my_list), 2).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With