pythonpython-itertoolspython-typing

How to specify types for itertools groupby?


I've a list of string to be operated upon. And the return type is something like group type consisting of int as a key and a list of string as value.

What i've tried?

from typing import List, Dict, Iterator

from itertools import groupby

def group_names(names: List[str]) -> Dict[int, list]:
    group_iter: Iterator[int, Iterator[list]]  = groupby(sorted(names,key=len), lambda x: len(x)) # -> Having an issue here
    return {k: list(v) for k, v in group_iter}

It works fine i type it as a Iterator consisting of Any type.

group_iter: Iterator[Any]  = groupby(sorted(names,key=len), lambda x: len(x))

But i want to specify type for group key as well as a items ?


Solution

  • Refering to this post i noticed that the return type of group by is:

    Iterable[Tuple[<key_type>, Iterable[<item_type>]]]

    So, the type in my case would be:

    group_iter: Iterator[Tuple[int, Iterable[str]]]  = groupby(sorted(names,key=len), lambda x: len(x))