将列表分组到字典

时间:2018-09-17 22:57:44

标签: python python-2.7

版本:python 2.7

列表如下:

select merchant
    , count(distinct customer) as count_customers
    , avg (amount) as avg_amount
    , ??? as avg_number_products_per_customer
from purchases
group by merchant

输出应为json格式,如下所示:

[ ['a', '1'], ['b','2'], ['c','3'], ['a', '11'], ['b','2'], ['c','31'], ['a', '1'], ['b','22'], ['c','3d'] ]

我尝试过lambda,

  [{
    "a": "1",
    "b": "2",
    "c": "3"
 }, {
    "a": "11",
    "b": "2",
    "c": "31"
 }, {
    "a": "1",
    "b": "22",
    "c": "3d"
 }]

我想知道如何将其分组以获得上述json格式?

2 个答案:

答案 0 :(得分:3)

对于您作为示例提到的数据,以下代码将起作用。

[dict(x) for x in zip(*[iter(z)]*3)]

如果在列表中每次出现('d', 4)之后添加额外的c,则在这种情况下可以将3替换为4

对于其他所有内容,我们需要更多的数据和您的示例代码作为工作量的证明。

答案 1 :(得分:0)

假设输入总是以3为一组,您可以这样做:

import json

data = [['a', '1'], ['b', '2'], ['c', '3'], ['a', '11'], ['b', '2'], ['c', '31'], ['a', '1'], ['b', '22'], ['c', '3d']]
result = [{k: v for k, v in data[i:i + 3]} for i in range(0, len(data), 3)]

print(json.dumps(result))

输出

[{"a": "1", "c": "3", "b": "2"}, {"a": "11", "c": "31", "b": "2"}, {"a": "1", "c": "3d", "b": "22"}]