大家好,我有一个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}]}]
谁有主意?
答案 0 :(得分:4)
使用itertools.groupby(并假设某些键和值周围的怪异间距是偶然的):
from itertools import groupby
values = [{"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}}]
def get_seller_id(d):
return d['seller_id']
groups = []
for seller_id, items in groupby(sorted(values, key=get_seller_id), get_seller_id):
groups.append({'seller_id': seller_id, 'list_item': list(items)})
print(groups)
答案 1 :(得分:1)
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
,然后以必要的格式将其展平。
不需要初步排序。
答案 2 :(得分:0)
这是一种构建字典的解决方案,然后将其展平为所需的格式,而第二种解决方案可以一次完成整个工作。
from collections import defaultdict
catalog = [
{"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}}
]
new_catalog = defaultdict(list)
for entry in catalog:
new_catalog[entry["seller_id"]].append(entry["item"])
result = [{"seller_id": i, "list_item": l} for i, l in new_catalog.items()]
print(result)
direct = [{"seller_id": i, "list_item": [c["item"] for c in catalog if c["seller_id"] == i]}
for i in set([c["seller_id"] for c in catalog])]
print(direct)
编辑:更改了空字典的手动构造,并改为使用defaultdict(list)添加新元素,因为这恰好满足了要求。