There seems to be no built-in way to get representation in the dictionary. The simplest workaround is the Jochen approach. I adapted his code slightly so that it worked for my purposes:
from collections import MutableMapping
class DictView(MutableMapping):
def __init__(self, source, valid_keys):
self.source, self.valid_keys = source, valid_keys
def __getitem__(self, key):
if key in self.valid_keys:
return self.source[key]
else:
raise KeyError(key)
def __len__(self):
return len(self.valid_keys)
def __iter__(self):
for key in self.valid_keys:
yield key
def __setitem__(self, key, value):
if key in self.valid_keys:
self.source[key] = value
else:
raise KeyError(key)
def __delitem__(self, key):
self.valid_keys.remove(key)
d = dict(a=1, b=2, c=3)
valid_keys = ['a', 'c']
d2 = DictView(d, valid_keys)
d2['a'] = -1
print d
So d2behaves like a dictionary in all aspects except printing, due to a different method __repr__(). Inheriting from dictto obtain __repr__()will require the re-implementation of each method, as is done for collections.OrderedDict. If only readonly browsing is required, you can inherit from collections.Mappingand save the implementation of __setitem__()and __delitem__(). I find it DictViewuseful to select parameters from self.__dict__and transfer them in a compact form.
source
share