Stack Exchange
How to convert complex tuples into JSON structure
Currently, I have two (large) lists like these:
labels = ['name1', 'name2', 'name3', 'name4', ...]
values = [5, 8, 6, 7, ...]

And I need to create a JSON output like this, using a loop: 
[{"value": 5, "label": "name1"}, {"value": 8, "label": "name2"}, {"value": 6, "label": "name3"}, {"value": 7, "label": "name4"}, ...]

I tried several examples of code around Internet, i.e.:
dictionary = [dict(zip(labels, values))]
data = json.dumps(values)
print data

But working with tuples seems to be a little harder. And the requirement of constant labels like "value" makes it more confuse for me.
Any suggestion?

Any suggestion? Here's one: Give this a shot yourself and come back if you run into trouble.

You could create a temporary list of dictionaries and pass it to json.dumps(). izip_longest() is used to gracefully handle the case where the two lists aren't the same size.
import json

try:
    from itertools import izip_longest
except ImportError:    # Python 3
    from itertools import zip_longest as izip_longest

labels = ['name1', 'name2', 'name3', 'name4']
values = [5, 8, 6, 7]

temp = [{'value': value, 'label': label}
            for label, value in izip_longest(labels, values, fillvalue='')]

print(json.dumps(temp))

Output:
[{"value": 5, "label": "name1"}, {"value": 8, "label": "name2"}, {"value": 6, "label": "name3"}, {"value": 7, "label": "name4"}]


How about:
print [{'value':a, 'label':b} for (a, b) in zip(values, labels)]


It worked perfect. I wonder how the JSON api was unnecessary at all to solve this problem! :O
