Create an array of dictionaries from a Python list

  • A+
Category:Languages

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.

 


One-liner using comprehension:

[{'value': k, 'score': v} for k, v in [my_list[i: i + 2] for i in range(0, len(my_list), 2)]]  [{'score': 2.75, 'value': 35}, {'score': 3.45, 'value': 67}] 

Using your original attempt:

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

Another more verbose way

from operator import itemgetter  getters = [itemgetter(slice(i, i + 2)) for i in range(0, len(my_list), 2)] vals = [g(my_list) for g in getters]   def score_vals(s):     k, v = s     return {'value': k, 'score': v}  list(map(score_vals, vals)) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: