How missing keys are handled in Dictionary (Hashtables) in C++, Python and MATLAB

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, dictionary objects (R2020b and on), unless you want to stick to valid MATLAB variable names as keys and exploit dynamic fieldnames.

Neither containers.Map() or dictionary 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 iskey()/isKey() method to check if the key exist first and decide to read it or spit out a default value.

Python

Natively Python dictionaries will throw a Key error exception if the requested key in [] operator (aka __getitem__()) do 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 one different class, not 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.

Loading