Reputation: 60
i have a list of ungrouped objects and i want to return a list of grouped objects by a common value
[{"name": "test", "group": "A"},{"name": "test2", "group": "B"},{"name": "test3", "group": "A"},{"name": "test4", "group": "B"}]
I want to return this
[{"group":"A","users":[{"name":"test"},{"name":"test3"}]}]
Upvotes: 1
Views: 60
Reputation: 16531
While Willem's answer is correct for the OP's question as asked, it is more common to want the grouping 'by' the common value and thus to want to obtain a mapping rather than a list thus:
from collections import defaultdict
users = [
{"name": "test", "group": "A"},
{"name": "test2", "group": "B"},
{"name": "test3", "group": "A"},
{"name": "test4", "group": "B"}]
users_by_group = defaultdict(list)
for user in users:
users_by_group[user['group']].append(user)
#users_by_group:
# A:
# - group: A
# name: test
# - group: A
# name: test3
# B:
# - group: B
# name: test2
# - group: B
# name: test4
Upvotes: 1
Reputation: 476719
You can use groupby
of itertools
:
from itertools import groupby
from operator import itemgetter
result = [
{ 'group': g, 'users': [{'name': v['name']} for v in vs] }
for k, vs in groupby(sorted(mylist, itemgetter('group')), itemgetter('group'))
]
Upvotes: 1