When trying to be all things to all people—a time- and memory-efficient data type for Python users, an internal data structure used as part of the interpreter's implementation, and a readable and maintainable code base for Python's developers—it's necessary to complicate a pure, theoretically elegant implementation with special-case code for particular cases… but not too much.
contains space for an eight-slot hash table. Small dictionaries with five elements or fewer can be stored
in this table, saving the time cost of an extra
malloc() call. This also improves cache
locality; for example,
structures occupy 124 bytes of space when using x86 GCC and
therefore can fit into two 64-byte cache lines. The dictionaries used for keyword arguments most commonly
have one to three keys, so this optimization helps improve
As previously explained, a single dictionary can contain keys of several different data types. In most Python programs, the dictionaries underlying class instances and modules have only strings as keys. It's natural to wonder whether a specialized dictionary object that only accepted strings as keys might provide benefits. Perhaps a special-case data type would be useful and make the interpreter run faster?
In fact, there is a string-specialized dictionary ...