Given a list of items and a key function, build a dictionary whose keys are key(item) and whose values are the lists of items sharing that key. Items within a group keep the order they had in the original list.
key is passed in as a real function — for example lambda s: s['city'] picks the city field of each record.
Example: with [{'n': 'a', 'c': 'X'}, {'n': 'b', 'c': 'Y'}, {'n': 'd', 'c': 'X'}] and lambda s: s['c'], the result groups the two X records together.
Implement this function:
def groupby(data: list, key: callable):
Write the function only — the arguments are read for you and the return value is printed automatically.
Input
[{'n': 'a', 'c': 'X'}, {'n': 'b', 'c': 'Y'}, {'n': 'd', 'c': 'X'}]
lambda s: s['c']
Output
{'X': [{'n': 'a', 'c': 'X'}, {'n': 'd', 'c': 'X'}], 'Y': [{'n': 'b', 'c': 'Y'}]}