IMPROVED: keysort before calling group_pairs_by_key