如何使用 itertools.groupby 格式化字典列表?

How do I format a list of dictionaries with itertools.groupby?

试图找到将字典列表格式化为特定 json 格式的最佳方式。目前我正在手动遍历字典数组。

我的阵列:

a = [{'sales': 2100, 'department_id': 66, 'department_name': 'dog', 'month':11},
     {'sales': 3900, 'department_id': 22, 'department_name': 'cat', 'month':12},
     {'sales': 2100, 'department_id': 66, 'department_name': 'cat','month':11},
     {'sales': 3900, 'department_id': 22, 'department_name': 'dog','month':12}]

预期结果:

b = [{"result":[{"month":11, 'sales': 2100},
                {"month":12, 'sales': 3900},]
      "meta":{"name":"cat"}
      "department_id": 22
     },
     {"result":[{"month":11, 'sales': 2100},
                {"month":12, 'sales': 3900},]
      "meta":{"name":"dog"}
      "department_id": 66
     }]

虽然可以按 groupby 排序,但我不想再次使用它来获取名称元数据。是否有另一个高效的 dict group bys 库?

如果你只想按 department_id 分组,你可以使用另一个字典进行分组,使用 defaultdict 按 id 分组并构建新的 k/v对按要求,不需要对数据进行排序:

a = [{'sales': 2100, 'department_id': 66, 'department_name': 'dog', 'month': 11},
     {'sales': 3900, 'department_id': 22, 'department_name': 'cat', 'month': 12},
     {'sales': 2100, 'department_id': 66, 'department_name': 'cat', 'month': 11},
     {'sales': 3900, 'department_id': 22, 'department_name': 'dog', 'month': 12}]

from collections import defaultdict

dct = defaultdict(lambda: {"result": [], "meta": "", "department_id": ""})

for d in a:
    _id = d['department_id']
    dct[_id]["result"].append({"sales": d["sales"], "month": d["month"]})
    dct[_id]["meta"] = d['department_name']
    dct[_id]["department_id"] = _id

from pprint import pprint as pp
pp(dct.values())

哪个会给你:

[{'department_id': 66,
  'meta': 'cat',
  'result': [{'month': 11, 'sales': 2100}, {'month': 11, 'sales': 2100}]},
 {'department_id': 22,
  'meta': 'dog',
  'result': [{'month': 12, 'sales': 3900}, {'month': 12, 'sales': 3900}]}]