Documentation

util.lists.groupby

Groups elements of a list by a specified key, returning a dictionary-like object whose keys are the group labels and whose values are lists of the items belonging to each group.

def groupby(
  lst: list = None, # Required
  key: str or function = None, # Required
) -> dict
  • lst: The list to group.
  • key: Either a string or a function.
    • If key is a string, each element in lst will be grouped by the value obtained from that string path (using a nested lookup).
    • If key is a function, the function must accept a single keyword argument named key. It will be called for each element in lst and should return the grouping value for that element.

Returns a dictionary-like object where each key is one of the group values, and each value is the list of items that share that group.

Example:

# Example list of dictionaries
people = [
  {"name": "Alice", "age": 30},
  {"name": "Bob",   "age": 30},
  {"name": "Eve",   "age": 40},
]

# Group by the 'age' field:
# {
#   "30": [
#     {"name": "Alice", "age": 30},
#     {"name": "Bob",   "age": 30}
#   ],
#   "40": [
#     {"name": "Eve",   "age": 40}
#   ]
# }
grouped = util.lists.groupby(lst=people, key="age")

# If you have a function key, define a DSL function that accepts key=...
# e.g.,
# def some_function(key=None):
#   return key["age"]
# grouped = util.lists.groupby(lst=people, key=some_function)