Someone needs to write a book on the theory and application of keyboard mapping

Trying to figure out which key on one of my keyboards does what in a given context (console, X, KDE, Gnome, etc.) is mind-boggling. I wonder if anybody fully understands the topic.

Perhaps not but, in simple terms, it has been possible since at least CP/M in the 1980s to map the signals from a particular key on a keyboard to a particular set of ASCII characters (each depending on whether SHIFT, ALT or another combination of keys is pressed at the same time); as long as you have a single keymap in operation, the key will always generate the same set of ASCII - now Unicode - characters.
If a key is producing different characters with different software, then you have more than one keymap in use rather than just one for all the software you are using.

A basic knowledge suffices: