There are some ways to create this kind of structure. You can make a recursive defaultdict (but some find the defaultdict output annoying). Or you could create a class that defines __missing__ and returns a new dict.
One problem is that it’s hard to distinguish between assigning to a position and just checking for existence. So just checking a value can bring a tree into existence (which often isn’t desired). You lose the protections you would otherwise have to warn when accessing unknown keys.
I’m against this. It would make typos in dictionary keys silently give wrong answers, rather than failing immediately like they currently do.
It’s possible to do this currently with a defaultdict(dict)[1], which explicitly signals that you want this behaviour. Making that behaviour part of the standard dictionary would mean that we’d need to add a new dictionary type that acted like dictionaries currently do - because there are definitely people who rely on the current behaviour. So all you’d be doing in practice is swapping which of dict and defaultdict(dict) is builtin, and which is a stdlib type. That’s effectively no benefit, for a huge backward compatibility cost.
Or, as @BowlOfRed notes, a recursive version if you want it to happen indefinitely deeply. ↩︎
if the key is not present and you attempt at accessing it, the default value would be {'def': 123}, otherwise you could give a value of your choice, like for the key 'ghi' the value is 10
Yes, but there is a slight difference. My main goal/request was not to set a custom dict as a default value; just an empty one. I believed this would bring out some easiness when working with complex structures. It doesn’t raise a key error, instead it adds an empty dict. There won’t be any need to check if parent key exists, or you won’t be asked for adding the parent key first.
So, there will not be any need for using setdefaults.
I have forgotten to make the default dict recursive in my last post’s example, sorry for that.
Btw, our tiny codes(the ones which include defaultdict) are just simple examples, they have some defects.
I have realized that it is a foolish idea with its current state since it literally blocks KeyError. But, adding a new default arg to __setitem__ can still be considered. (strict is the name, True is the default value).