for key, groups in groupby(sorted_permissions, permissions_key):
    key_result = {}
groups = list(groups)
key_result[id_key] = key
if name_key is not None:
    key_result[name_key] = groups[0][name_key]
key_result[groups_key] = [{k: v for k, v in group.items() if k !=
    id_key and (name_key is None or k != name_key)} for group in groups]
result.append(key_result)
return result

def change_format(initial):
    pass
Sort and group a list of dictionaries