Specify argument and return types of dict transpose function
03:49 28 Aug 2023

This function transposes a given dict with set values:

from collections import defaultdict

def transpose_dict(dct: dict[int, set[int]]) -> dict[int, set[int]]:

    transposed = defaultdict(set)

    for key, value_set in dct.items():
        for inv_key in value_set:
            transposed[inv_key].add(key)
            
    return dict(transposed)

By the typing I used, the function is restricted to dictionaries with int keys and sets of int values only, although the type int itself is fairly irrelevant to the function implementation.

On the contrary, it would look pretty much the same even for str, tuple, etc. (or combinations thereof). The obvious option dict[Any, set[Any] seems too weak to me, since it does not reflect the swapping of the types of key and value.

How can I express a transposable dict type (dict[A, set[B]]dict[B, set[A]]) and its transposition type?

python python-typing mypy type-hinting