您可以从此处稍微修改代码以添加large_keys
属性。现在,每当添加其中一个大纪元时,字典都会跟踪它们。当你想迭代它们时,你可以简单地迭代那个属性。
class MyUpdateDict(dict):
def __init__(self, *args, **kwargs):
self.large_keys = []
self.update(*args, **kwargs)
def __setitem__(self, key, value):
# optional processing here
if int(key)>1363033000:
self.large_keys.append((key,value))
super(MyUpdateDict, self).__setitem__(key, value)
def update(self, *args, **kwargs):
if args:
if len(args) > 1:
raise TypeError("update expected at most 1 arguments, got %d" % len(args))
other = dict(args[0])
for key in other:
self[key] = other[key]
for key in kwargs:
self[key] = kwargs[key]
def setdefault(self, key, value=None):
if key not in self:
self[key] = value
return self[key]
这可能过于简单,因为大值是硬编码的,但您可以修改以使其更合适。