Type-safe version of getting the keys of a dict, sorted by value

Given the results dict, if I want to get a sequence containing the keys of that dict sorted by the values, I can use the simple idiom: sorted(results, key=results.get, reverse=True)
The trouble is that, assuming that the keys aren’t a type comparable with None (and writing that type as I), the return type of results.get is I|None. My type checker gives me a type warning because not knowing that all the values that will be passed to results.get will make it return an I, it deduces that an I could be compared with None.

Is there another solution than using # type: ignore which would shut off all checks on that line ?
Another solution which would preferably be simple both in writing and in complexity.

Does using results.__getitem__ instead of results.get do the trick?

Hm, it does, though I would prefer to avoid using dunders in plain code…
But it would most likely be faster at execution than get.

Maybe wrapped in something that does a cast.

from typing import cast

def sure_get(x: str) -> int:
    return cast(int, results.get(x))

sorted(results, key=sure_get, reverse=False)

Well, I wrote int being the example that I tried.

key=lambda k: results[k]?

1 Like