Create a Json from a tuple - python -


i'm using python sql query returns result below:

print (123.0, 460654.05) (234.0, 292016.43) (1231.0, 271915.11) (234.0, 189367.59) (1.0, 117566.06) (2.0, 100600.76000000001) (3.0, 90443.32) (4.0, 84218.40000000001) (5.0, 82793.86) (7.0, 77368.06) 

it's tuple.

my idea create json result above this:

{'items': [{'value': 123.0, 'label': '460654.05)'}, {'value': 234.0, 'label': '292016.43)'}], , on, 'auth_token': 'mysecret'} 

i tried using for.

for in res:     n = {'items': [{'label': '0', 'value': '0', 'auth_token':                     'hues4onpdhti2'}]}     n['items'][0]['label'] = i[0]     n['items'][0]['value'] = i[1] 

the result was

{'items': [{'auth_token': 'mysecret', 'value': 460654.05, 'label': 123.0}]} {'items': [{'auth_token': 'mysecret', 'value': 292016.43, 'label': 234.0}]} 

any ideas?

you can use list comprehension this:

[dict(zip(['label', 'value'], list(item))) item in data] 

i assuming data list of tuples returned sql query

demo:

in [25]: data = [(123.0, 460654.05),    ....: (234.0, 292016.43),    ....: (1231.0, 271915.11),    ....: (234.0, 189367.59),    ....: (1.0, 117566.06),    ....: (2.0, 100600.76000000001),    ....: (3.0, 90443.32),    ....: (4.0, 84218.40000000001),    ....: (5.0, 82793.86),    ....: (7.0, 77368.06)] in [26]: interim_data = [dict(zip(['label', 'value'], list(item))) item in data] in [27]: result = {'items': interim_data, 'auth_token': 'mysecret'} 

this gives:

in [28]: result out[28]: {'items': [{'label': 123.0, 'value': 460654.05},   {'label': 234.0, 'value': 292016.43},   {'label': 1231.0, 'value': 271915.11},   {'label': 234.0, 'value': 189367.59},   {'label': 1.0, 'value': 117566.06},   {'label': 2.0, 'value': 100600.76000000001},   {'label': 3.0, 'value': 90443.32},   {'label': 4.0, 'value': 84218.40000000001},   {'label': 5.0, 'value': 82793.86},   {'label': 7.0, 'value': 77368.06}],   'auth_token': 'mysecret' } 

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -