Python create own dict view of subset of dictionary

后端 未结 3 738
情深已故
情深已故 2021-01-13 05:32

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 di         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-13 06:13

    To clarify the semantics, you're thinking of something like this:?

    class FilteredDictView:
        def __init__(self, base_dict, test):
            self._base_dict = base_dict
            self._test = test
        def __getitem__(self, key):
            value = self._base_dict[key] # might throw KeyError
            if not self._test(key,value):
                throw KeyError(key)
            return value
        # ... implement remaining dict-like-methods ...
    

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

提交回复
热议问题