I'm using nested dictionaries as implemented using the AutoVivification class answer at What is the best way to implement nested dictionaries?; namely
class AutoVivification(dict):
"""Implementation of perl's autovivification feature."""
def __getitem__(self, item):
try:
return dict.__getitem__(self, item)
except KeyError:
value = self[item] = type(self)()
return value
a = AutoVivification()
a['foo']['bar'] = 'spam'
thus permitting arbitrary nesting in the dictionary. Is there a way to modify the class such that one could assign values to members using an arbitrary set of keys, but only previously defined sets of keys are allowed when trying to access / read from the member? For example,
print a['foo']['bar']
print a['foo']['eggs']
currently outputs
spam
{}
It would be great if the second one gave an error instead, as a['foo']['eggs'] hasn't been defined...