2

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

Selcuk
  • 57,004
  • 12
  • 102
  • 110
Luca
  • 10,458
  • 24
  • 107
  • 234
  • 1
    As far as I know, the only way to do this properly is with a TypedDict. Have you had a look at https://www.python.org/dev/peps/pep-0589/? – Karl Sep 02 '20 at 06:17
  • Duplicate for fixed keys: [Python 3 dictionary with known keys typing](https://stackoverflow.com/q/44225788/7851470) – Georgy Sep 02 '20 at 09:18

1 Answers1

6

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.

Selcuk
  • 57,004
  • 12
  • 102
  • 110
  • 2
    Union here would mean int and float are accepted on all fields. If it is important to differentiate which keys accept int and which accept float then this would be too general. Granted though, OP didn't make that distinction in his question – Karl Sep 02 '20 at 06:24
  • 2
    @Karl True. In that case your `TypedDict` suggestion makes more sense. – Selcuk Sep 02 '20 at 06:25
  • I will investigate this `TypedDict` think as the structur of the Dict is fixed – Luca Sep 02 '20 at 06:52