Python create own dict view of subset of dictionary

后端 未结 3 776
情深已故
情深已故 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:25

    This is pretty easy to implement:

    from collections import Mapping
    class FilteredItems(Mapping):
        def __init__(self, source, filter):
            self.source = source
            self.p = filter
    
        def __getitem__(self, key):
            x = self.source[key]
            if self.p(key,x):
                return key,x
            else:
                raise KeyError(key)
    
    
    d2 = FilteredItems(d, some_test)
    

提交回复
热议问题