title: How do I type annotate using any type as a key in a Python dictionary?
body: <p>In Python, types are first class objects.  As such, I can create a dictionary with types as the keys.  For example:</p>
  <pre><code>mydict = {
      int: &quot;Hello!&quot;,
      str: 12,
      SomeClassName: &quot;Hello again!&quot;}
  </code></pre>
  <p>Assuming that my dictionary will be populated with arbitrary types as keys, how do I type annotate that?</p>
  <p>I've tried:</p>
  <pre><code>mydict: dict[type, Any] = {
      int: &quot;Hello!&quot;,
      str: 12,
      SomeClassName: &quot;Hello again!&quot;}
  </code></pre>
  <p>and:</p>
  <pre><code>mydict: dict[Type[Any], Any] = {
      int: &quot;Hello!&quot;,
      str: 12,
      SomeClassName: &quot;Hello again!&quot;}
  </code></pre>
  <p>and even:</p>
  <pre><code>mydict: dict[Any, Any] = {
      int: &quot;Hello!&quot;,
      str: 12,
      SomeClassName: &quot;Hello again!&quot;}
  </code></pre>
  <p>But <code>mypy</code> complains about the assignment for all of those. What is the proper way to type annotate a dictionary that takes any type as a key?</p>
  <p>If I had just certain types like <code>int</code> and <code>str</code>, I could probably annotate it as <code>dict[Union[Type[int], Type[str]]], Any]</code> but since I want to support keys of <em>any</em> type, that just doesn't cut it.</p>
  <p>Without the type annotation, the syntax works fine and I can even retrieve specific values from the dictionary. For example:</p>
  <pre><code>mydict = {
      int: &quot;Hello!&quot;,
      str: 12,
      SomeClassName: &quot;Hello again!&quot;}
  
  print(mydict[int])
  </code></pre>
  <p>...and it succesfully prints out <code>Hello!</code></p>
  <p>If it matters any, I'm using Python 3.9.6 and mypy 0.812.</p>