在python中转换列表

在python中转换列表

大家好,我有一个json

[{"seller_id": 3, "item": {"product_id": 4, "amount": 1, "id": 9}},
 {"seller_id": 1, "item": {"product_id": 1 , "amount": 2, "id": 10}},
 {"seller_id": 3, "item": {"product_id": 3, "amount": 2, "id": 11}},
 {"seller_id ": 1," item ": {" product_id ": 2," amount ": 2," id ": 12}}]


我想分组在一起,这意味着相同的卖家将再次分组该项目

返回的结果如下:

[{"seller_id": 3, "list_item": [{"product_id": 4, "amount": 1, "id": 9},
 {"product_id": 3, "amount": 2, "id": 11}]},
 {"seller_id": 1, "list_item": [{"product_id": 1, "amount": 2, "id": 10},
 {"product_id": 1, "amount": 2, "id": 10}, {"product_id": 2, "amount": 2, "id": 12}]}]


谁有主意?

最佳答案

from collections import defaultdict

data = [
    {"seller_id": 3, "item": {"product_id": 4, "amount": 1, "id": 9}},
    {"seller_id": 1, "item": {"product_id": 1, "amount": 2, "id": 10}},
    {"seller_id": 3, "item": {"product_id": 3, "amount": 2, "id": 11}},
    {"seller_id": 1, "item": {"product_id": 2, "amount": 2, "id": 12}}
]

grouped = defaultdict(list)
flattened = []

for item in data:
    grouped[item['seller_id']].append(item['item'])

for k, v in grouped.items():
    flattened.append({'seller_id': k, 'list_item': v})

print(flattened)


另一种选择是使用defaultdict,然后以必要的格式将其展平。

不需要初步排序。

关于python - 在python中转换列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54228100/

10-14 18:08