C++
In C++ (STL), the default behavior to touching (especially reading) a missing key (whether it’s map or unordered_map, aka hashtable) is that the new key will be automatically inserted with the default value for the type (say 0 for integers).
I have an example MapWithDefault template wrapper implementation that allows you to endow the map (during construction) with a default value to be returned when the key you’re trying to read does not exist
C++ has the at() method but it involves throwing an exception when the key is not found. However enabling exceptions is a material performance overhead burden in C++.
MATLAB
MATLAB’s hashtables are done with containers.Map() and with more modern MATLAB, , unless you want to stick to valid MATLAB variable names as keys and exploit dynamic fieldnames.dictionary objects (R2020b and on)
Neither containers.Map() or have a default value mechanism when a key is not found. It will just throw an error if the key you are trying to read does not exist. Use dictionaryiskey()/isKey() method to check if the key exist first and decide to read it or spit out a default value.
[UPDATE (2026-07-21)] the comment section pointed out that the new lookup method (introduced in R2023b) for dictionary objects (introduced in R2022b) provides a default value mechanism like Python’s .get(key, default) method. I cannot find a native mechanism to endow the default value into the dictionary object itself at the time of writing though. Thanks pete for pointing this out!
Python
Natively Python dictionaries will throw a Key error exception if the requested key in [] operator (aka __getitem__()) does not already exist.
Use .get(key, default) method if you want to assume a default value if the key is not found. The .get() method does not throw an exception: the default is None if not specified.
If you want C++’s default behavior of reading a new key means inserting the said key with a default, you have to explicitly import collections package and use defaultdict. I wouldn’t recommend this as the behavior is not intuitive and likely confusing in insidious ways.
There’s a simiar approach to my MapWithDefault in Python dictionaries: subclass from dict and define your own __missing__ dunder/magic method that returns a default when a key is missing, then use the parent (aka dict)’s constructor to do an explicit (type/class) conversion for existing dict object into your child class object that has __missing__ implemented.
Despite this approach is a little like my MapWithDefault, the __missing__ approach has more flexibility like allowing the default value to be dependent on the query key string, but it comes at the expense of making up a different class (namely a subclass of dict), not making a different instance per different default values.
Monkey-patching instance methods is frowned upon in Python. So if you want the default value to tie to instances, the mechanism needs to be redesigned.
![]()