We have a list of dictionaries:
example = [
{'a': 11, 'b': 2, 'c': 3},
{'a': 11, 'b': 22, 'c': 33},
{'a': 11, 'b': 222, 'c': 333}
]
How to group the dictionaries by repeating key a?
example = {
11: [
{'b': 2, 'c': 3},
{'b': 22, 'c': 33},
{'b': 222, 'c': 333}
]
}
>Solution :
Grouping can be done using itertools.groupby.
Make an iterator that returns consecutive keys and groups from the iterable. The key is a function computing a key value for each element. If not specified or is None, key defaults to an identity function and returns the element unchanged. Generally, the iterable needs to already be sorted on the same key function.
from itertools import groupby
example = [
{'a': 11, 'b': 2, 'c': 3},
{'a': 11, 'b': 22, 'c': 33},
{'a': 11, 'b': 222, 'c': 333}
]
for k, g in groupby(example, key=lambda v: v.pop("a", None)):
print(k, list(g))
Output:
11 [{'b': 2, 'c': 3}, {'b': 22, 'c': 33}, {'b': 222, 'c': 333}]