[Python-Dev] Add a "transformdict" to collections

Victor Stinner victor.stinner at gmail.com
Wed Sep 11 15:58:35 CEST 2013

2013/9/11 Steven D'Aprano <steve at pearwood.info>:
> But the proposal is not for a case-insensitive dict. It is more general
> than that, with case-insensitivity just one specific use-case for such
> a transformative dict. Arguably the most natural, or at least obvious,
> such transformation, but there are others.
> I have code that does something like this:
> MAPPING = {'spam': 23, 'ham': 42, 'eggs': 17}
> result = MAPPING[key.strip()]
> # later...
> answer = MAPPING[key]  # Oops, forgot to strip! This is broken.

For this use case, you should not keep the key unchanged, but it's
better to store the stripped key (so MAPPING.keys() gives you the
expected result). The transformdict type proposed by Antoine cannot be
used for this use case.

The os.environ mapping uses a subprocess of MutableMapping which
accepts 4 functions: encoder/decoder for the key and encoder/decoder
for the value. Such type is even more generic. transformdict cannot
replace os._Environ.

(Or do you prefer to store the ' eggs' key?)


More information about the Python-Dev mailing list