Search code examples
pythonpython-3.xtype-hintingtyping

typing Dict with multiple key value types


I have a python function which returns a dictionary with the following structure

{
   (int, int): {string: {string: int, string: float}}
}

I am wondering how I can specify this with type hints. So, these bits are clear:

Dict[Tuple[int, int], Dict[str, Dict[str, # what comes here]]

However, the internal dictionary has int and float value types for the two keys. I am not sure how to annotate that


Solution

  • You should be able to use Union:

    Union type; Union[X, Y] means either X or Y.

    from typing import Union
    
    Dict[Tuple[int, int], Dict[str, Dict[str, Union[int, float]]]
    

    That being said, it might be a better idea to use a tuple or a namedtuple in place of the inner dict if the keys are always the same.