Skip to content

Instantly share code, notes, and snippets.

@rafalkrupinski
Last active January 11, 2023 23:05
Show Gist options
  • Save rafalkrupinski/4d796622c8bf5191d6e1764be3e593bc to your computer and use it in GitHub Desktop.
Save rafalkrupinski/4d796622c8bf5191d6e1764be3e593bc to your computer and use it in GitHub Desktop.
In this example, the TypeFilteredDictView class takes two arguments d which is a dictionary and value_type which is the type you want to filter by. The class implements the __getitem__, __iter__ and __len__ methods of the collections.abc.MappingView interface, so that it behaves like a view of the original dictionary. The class internally use di…
import collections.abc
class TypeFilteredDictView(collections.abc.MappingView):
def __init__(self, d, value_type):
self._d = d
self._value_type = value_type
def __getitem__(self, key):
return self._d[key]
def __iter__(self):
return (k for k, v in self._d.items() if isinstance(v, self._value_type))
def __len__(self):
return sum(1 for v in self._d.values() if isinstance(v, self._value_type))
# Usage example
d = {'a': 1, 'b': 'hello', 'c': [1, 2, 3], 'd': 4.5}
int_values = TypeFilteredDictView(d, int)
print(int_values) # Output: TypeFilteredDictView({'a': 1, 'd': 4})
@rafalkrupinski
Copy link
Author

In this example, the TypeFilteredDictView class takes two arguments d which is a dictionary and value_type which is the type you want to filter by. The class implements the getitem, iter and len methods of the collections.abc.MappingView interface, so that it behaves like a view of the original dictionary.
The class internally use dictionary comprehension to iterate through the key-value pairs of the dictionary, and only include the key that contains a value of the specified type.

In the usage example the object int_values is a view of the original dictionary that only includes keys whose values are of type int.

It also use the special method len to return the number of keys whose values are of the specified type.

Note: MappingView is only available in python version 3.3 and later. If you need to support earlier versions you can use collections.abc.Mapping and collections.abc.Sequence to mimic the behavior of a MappingView.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment