Q:

how to group dictionaries using itemgetter

I have a list of dictionaries like this:
students = [
    {'name': 'alex','class': 'A'},
    {'name': 'richard','class': 'A'},
    {'name': 'john','class': 'C'},
    {'name': 'harry','class': 'B'},
    {'name': 'rudolf','class': 'B'},
    {'name': 'charlie','class': 'E'},
    {'name': 'budi','class': 'C'},
    {'name': 'gabriel','class': 'B'},
    {'name': 'dessy', 'class': 'B'}
]

I would like to group these dictionaries by class, append them to a list and append each list to a list:
[[{'name': 'alex', 'class': 'A'},
 {'name': 'richard', 'class': 'A'}],
 [{'name': 'harry', 'class': 'B'},
 {'name': 'rudolf', 'class': 'B'},
 {'name': 'gabriel', 'class': 'B'},
 {'name': 'dessy', 'class': 'B'}],
 [{'name': 'john', 'class': 'C'},
 {'name': 'budi', 'class': 'C'}],
 [{'name': 'charlie', 'class': 'E'}]]

I know how to sort the previous list, using itemgetter:
import itertools
from operator import itemgetter
students = sorted(students, key=itemgetter('class'))

How can I group-append them in a list and create a list of lists? Also, would using sets be better in this case (order would not matter, as long as the dictionaries are grouped by class).

A:

You can do it with defaultdict
from collections import defaultdict

res = defaultdict(list)
for i in students:
    res[i['class']].append(i)
print(list(res.values()))

Output
[[{'name': 'alex', 'class': 'A'}, {'name': 'richard', 'class': 'A'}],
 [{'name': 'john', 'class': 'C'}, {'name': 'budi', 'class': 'C'}],
 [{'name': 'harry', 'class': 'B'},
  {'name': 'rudolf', 'class': 'B'},
  {'name': 'gabriel', 'class': 'B'},
  {'name': 'dessy', 'class': 'B'}],
 [{'name': 'charlie', 'class': 'E'}]]

