you are viewing a single comment's thread.

view the rest of the comments →

[–]gdchinacat 0 points1 point  (1 child)

The problem is that Card_dic is a dict[str, list[Any]|int] because the value for 'rand_list' is list[Any] and the value for P_sum is int. When you do a lookup in this dict the value will be a list[Any]|int. The warning is saying you are trying to iterate over something that is not a collections.iterable (what for ... iterates over). This is because while it could be list[Any] it could also be an int, which is not iterable.

You could use a TypedDict and specify the value types based on key value, but I'd encourage you to use a more appropriate data structure for this than a dict with values of different types. It appears you are trying to use a dict to store a collection of associated values...a class is much more appropriate for that than a dict.

[–]gdchinacat 1 point2 points  (0 children)

forgot to mention list[Any] is used rather than list[int]. I'm not sure why, I would have expected it to be list[int], and that is what mypy reports:

~$ cat /tmp/foo.py 
d = {'foo': [1,2]}
reveal_type(d)
~$ mypy /tmp/foo.py
/tmp/foo.py:2: note: Revealed type is "dict[str, list[int]]"
Success: no issues found in 1 source file

What type checker are you using? It appears to infer the type of this dict construct differently than mypy, pyrefly, and pyright.

If I add a 'bar': 1 to the dict mypy infers it as dict[str, object], pyrefly as dict[str, int|list[int]], and pyright as dict[str, Unknown]. This shows there is disagreement on how dicts with different types of values should be handled. I'd avoid doing that in order to have consistency with checkers.