Group list elements

Python, List, Dictionary · Nov 2, 2020

Groups the elements of a list based on the given function.

  • Use collections.defaultdict to initialize a dictionary.
  • Use fn in combination with a for loop and dict.append() to populate the dictionary.
  • Use dict() to convert it to a regular dictionary.
from collections import defaultdict

def group_by(lst, fn):
  d = defaultdict(list)
  for el in lst:
    d[fn(el)].append(el)
  return dict(d)
from math import floor

group_by([6.1, 4.2, 6.3], floor) # {4: [4.2], 6: [6.1, 6.3]}
group_by(['one', 'two', 'three'], len) # {3: ['one', 'two'], 5: ['three']}

More like this

  • Count grouped elements

    Groups the elements of a list based on the given function and returns the count of elements in each group.

    Python, List · Nov 2, 2020

  • Bifurcate list based on function

    Splits values into two groups, based on the result of the given filtering function.

    Python, List · Nov 2, 2020

  • List difference based on function

    Returns the difference between two lists, after applying the provided function to each list element of both.

    Python, List · Nov 2, 2020