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