我有一个未分组对象的列表,我想按一个公共值返回一个分组对象的列表
[{"name": "test", "group": "A"},{"name": "test2", "group": "B"},{"name": "test3", "group": "A"},{"name": "test4", "group": "B"}]
我要退货
[{"group":"A","users":[{"name":"test},{"name":"test3"}]}]
答案 0 :(得分:1)
虽然威廉姆(Willem)的答案对所提出的OP的问题是正确的,但更常见的是希望按“共同”值进行分组,因此希望获得映射而不是列表:
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
答案 1 :(得分:0)
您可以使用groupby
中的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'))
]