Slamice
Slamice

Reputation: 683

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

Trying to find the most optimal way to format a list of dicts to a specific json format. Currently I'm looping through the array of dicts manually.

My array:

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

Expected result:

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

While sorting by groupby is possible, I'd rather not use it again for grabbing the name meta data. Is there another efficient library for dict group bys?

Upvotes: 1

Views: 292

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180411

If you just want to group by department_id you can use another dict to do the grouping, using a defaultdict to group by id and constructing the new k/v pairs as required, there is no need to sort the data:

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

Which will give you:

[{'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}]}]

Upvotes: 1

Related Questions