I have the following lists :
valuevalues = [4, 5, 35, 23, 16, 7, 12] labelvalues = ['john', 'joe', 'Pier', 'Paul', 'Moe', 'Jane', 'Ruth'] labels = ['label' for i in range(len(valuevalues))] values = ['value' for i in range(len(valuevalues))]
And I would like to generate the following dictionaries:
[{'label': 'john', 'value':4}, {'label': 'joe', 'value':5}, {'label': 'Pier', 'value':35}, ... {'label': 'Ruth', 'value':12}]
Which kind of loop or function Should I use?
Advertisement
Answer
Use zip
and the following comprehension:
[{"label": l, "value": v} for l, v in zip(labelvalues, valuevalues)] # [{'label': 'john', 'value': 4}, {'label': 'joe', 'value': 5}, # {'label': 'Pier', 'value': 35}, {'label': 'Paul', 'value': 23}, # {'label': 'Moe', 'value': 16}, {'label': 'Jane', 'value': 7}, # {'label': 'Ruth', 'value': 12}]