As the many questions on the topic here on SO attest, taking a slice of a dictionary is a pretty common task, with a fairly nice solution:
{k:v for k,v in dict.viewitems() if some_test(k,v)}
But that creates a new dictionary, with its own mappings. For many operations, it would be nice to just have an immutable view of the original dict (i.e. it does not support assignment or deletion operations on the view). Implementing such a type is probably easy, but it's not good to have a proliferation of local utility classes.
So, my question is: is there a built-in way of obtaining such a "subset view"? Or is there a third-party library (preferably available via PyPi) that provides a good implementation of such a utility?
To clarify the semantics, you're thinking of something like this:?
If so, then I don't know of any such third party class. If you want to make implementing the remaining methods a little easier, you might look at using "UserDict" as a base class, which is basically just a wrapper for dict (the "UserDict.data" attribute is used to store the wrapped dict).
This is pretty easy to implement:
There seems to be no builtin way to obtain a view into a dictionary. The easiest workaround appears to be Jochen's approach. I adapted his code slightly to make it work for my purposes:
So
d2
behaves like a dictionary in all aspects except for printing, due to the different__repr__()
method. Inheriting fromdict
to get__repr__()
would require reimplementation of each and every method, as is done forcollections.OrderedDict
. If one wants only a readonly view, one can inherit fromcollections.Mapping
and save the implementation of__setitem__()
and__delitem__()
. I findDictView
useful to select parameters fromself.__dict__
and pass them on in a compact form.