There are at least two decent implementations of nested dictionary I’ve come across on SO, one is to use defaultdict, and the other is to subclass dict.
Both methods work fine for most functionalities, except that they both have a side-effect when accessing a non-existent key-value pair: it creates an empty dictionary for that key, stores that and returns it.
Ideally, I would like an implementation which would return None without creating an entry (e.g. an empty dictionary) upon an attempted access to a non-existent key. Is this feasible?
p.s. I am aware that we can avoid nested dictionary by using tuples as keys, but this implementation does not work me as I need to access the collection of entries at each level of the nested dictionary.
You must give up your requirement of returning None if you wish
d[key][subkey] = valueto work with missing keys. Ifd[key] is None,d[key][subkey] = valueis equivalent toNone[subkey] = value, which cannot work.What you can do with missing values is to return an empty dict-like object without assigning it to a key just yet. If that object holds a reference to the parent, the assignment can be delayed until there is an explicit assignment down the hierachy.
An example implementation (this is incomplete, you must do more than override setitem to have a fully functional dict subclass):
An alternative approach would be to override
__getitem__and__setitem__to do a nested lookup when the key is a tuple. This version gives a KeyError from__getitem__for missing keys in order to be consistent with regular dict. You can change it easily to return None instead if you wish.