Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyCharm Warning: Unexpected type for filter on dictionary

Tags:

python

pycharm

I have the following code in PyCharm:

LOCATIONS = {'loc1': [a, b, c], 'loc2': [d, e], 'loc3': [f, g]}
labels = ['loc2', 'loc3']
task_locations = dict(filter(lambda location: location[0] in labels, LOCATIONS.items()))

PyCharm issues the following warning on filter(lambda location: location[0] in labels, LOCATIONS.items()):

Unexpected type(s):
(Iterator[str])
Possible types:
(Mapping)
(Iterable[Tuple[Any, Any]])

How should I act on the warning? The same expression, but on a Dict[str, int], is without the warning. So I guess it has something to do with the LOCATIONS being a Dict[str, List[str]].

like image 544
Bato Avatar asked Aug 31 '25 22:08

Bato


1 Answers

It's a false positive from PyCharm. It thinks that filter will return Iterator[str] which is not the case, as its input is dict_items which is an Iterable[Tuple[Any, Any]].

You can also simplify the code like this:

task_locations = {k: v for k, v in LOCATIONS.items() if k in labels}

and PyCharm doesn't complain in this case.

like image 55
Agost Biro Avatar answered Sep 04 '25 19:09

Agost Biro