Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over TypedDict's keys

Here's an example:

from typing import TypedDict

class Foo(TypedDict):
    a: str
    b: int

foo = Foo(a='2', b=4)

for key in foo:
    print(foo[key])

I get

main.py:10: note: Revealed type is 'Any'
main.py:10: error: TypedDict key must be a string literal; expected one of ('a', 'b')
Found 1 error in 1 file (checked 1 source file)

I find this surprising - isn't it known that key is one of foo's keys, and hence that foo[key] should be valid?


Playground URL: https://mypy-play.net/?mypy=latest&python=3.9&gist=8972284897f25314f9c790eab4cb8548

like image 898
ignoring_gravity Avatar asked Aug 06 '26 00:08

ignoring_gravity


1 Answers

I think it's known issue which was discussed here. If you want it to work now, just try # type: ignore which should overwritten the warning.

from typing import TypedDict

class Foo(TypedDict):
    a: str
    b: int

foo = Foo(a='2', b=4)

for key in foo:
    print(foo[key]) # type: ignore

playground URL:https://mypy-play.net/?mypy=latest&python=3.9&gist=85e30e0187088219797a283c31d7ec7c

like image 148
Zichzheng Avatar answered Aug 07 '26 12:08

Zichzheng



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!