Default Dictionary
The built-in dictionary type considers it to be an error when you try to access the value for a key that doesn't exist. It will raise a KeyError
, which you have to handle or your program crashes. Often, that's a good idea. If the programmer doesn't get the key correct, it could indicate a typo or a misunderstanding of how the dictionary is used.
It's often a good idea, but not always. Sometimes, it's reasonable that a programmer doesn't know what the dictionary contains; whether it's created from a file supplied by the user or the content of a network request, for example. In situations like this, any of the keys the programmer expects could be missing, but handling KeyError
instances everywhere will be tedious, repetitive, and make the intent of the code harder to see.
For these situations, Python provides the collections.defaultdict
type. It works like a regular dictionary, except that you can give it a function that creates...