0

I was wondering if it is possible to define the type of keys and values of a dictionary can take when you initialise a dict.

I was expecting something like that :

myDict = dict(int, aClass)

or

myDict = dict[int, aClass]

i know how to declare a dictbut what i want is to code "This dict can only take a int as key and an instance of MyClass as a value"

but it does not work.

Thank you very much!

FinnStark

FinnStark
  • 30
  • 4
  • I believe that your question has already been answered [here](https://stackoverflow.com/questions/37087457/difference-between-defining-typing-dict-and-dict) – Theodoros Siklafidis Apr 02 '20 at 17:24
  • Thanks Theodoros, typing.Dict[int, int] works but typing.Dict[int, MyClass] does not works : TypeError: Parameters to generic types must be types. Got – FinnStark Apr 03 '20 at 16:48

1 Answers1

0
myDict = {
    "key1": "value1"
}
tjfuller
  • 186
  • 1
  • 3
  • i know how to declare a dict, ty but what i want is to write "This dict can only take a int as key and an instance of MyClass as a value" – FinnStark Apr 03 '20 at 16:49
  • I don’t think that python supports this as a dynamically typed language the same way that something like java has things like Map. You could write your own class that wraps a dictionary and checks the object types at runtime but you won’t be able to have it fail at “compile time” (although that doesn’t really exist for python anyway). – tjfuller Apr 03 '20 at 18:00