从元组 - python创建一个Json

时间:2014-08-18 21:26:16

标签: python json

我使用python做一个返回以下结果的SQL查询:

print i
(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)

它是一个元组。

我的想法是使用上面的结果创建一个Json:

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

我尝试过使用for。

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

结果是

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

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

你可以使用这样的列表理解:

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

我假设data是SQL查询返回的元组列表

演示:

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))) for item in data]
In [27]: result = {'items': interim_data, 'auth_token': 'mysecret'}

这给出了:

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'
}

答案 1 :(得分:1)

也许这就是你要找的东西:

   results = [(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)]

    grouped = {
        'items': []
    }

    for d in results:
        grouped.get('items').append({
            'auth_token': 'mysecret',
            'label': d[0],
            'value': d[1]
        })

    print grouped