Search code examples
pythonpycharm

PyCharm Warning: Unexpected type for filter on dictionary


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]].


Solution

  • 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.