def _group_proteins(proteins, peptides):
    """Group proteins when one's peptides are a subset of another's.

    WARNING: This function directly modifies `peptides` for the sake of
    memory.

    Parameters
    ----------
    proteins : dict[str, set of str]
        A map of proteins to their peptides
    peptides : dict[str, set of str]
        A map of peptides to their proteins

    Returns
    -------
    protein groups : dict[str, set of str]
        A map of protein groups to their peptides
    peptides : dict[str, set of str]
        A map of peptides to their protein groups.
    """
    grouped = {}
    for prot, peps in sorted(proteins.items(), key=lambda x: -len(x[1])):
        if not grouped:
            grouped[prot] = peps
            continue

        matches = set.intersection(*[peptides[p] for p in peps])
        matches = [m for m in matches if m in grouped.keys()]

        # If the entry is unique:
        if not matches:
            grouped[prot] = peps
            continue

        # Create new entries from subsets:
        for match in matches:
            new_prot = ", ".join([match, prot])
            # Update grouped proteins:
            grouped[new_prot] = grouped.pop(match)

            # Update peptides:
            for pep in grouped[new_prot]:
                peptides[pep].remove(match)
                if prot in peptides[pep]:
                    peptides[pep].remove(prot)

                peptides[pep].add(new_prot)

    return grouped, peptides