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

Antoine Pitrou solipsis at pitrou.net
Tue Sep 10 11:28:32 CEST 2013


In http://bugs.python.org/issue18986 I proposed adding a new mapping
type to the collections module.

The original use case is quite common in network programming and
elsewhere (Eric Snow on the tracker mentioned an application with stock
symbols). You want to have an associative container which matches keys
case-insensitively but also preserves the original casing (e.g. for
presentation). It is a commonly reimplemented container.

It is also an instance of a more general pattern: match keys after
applying a derivation (or coercion) function, but at the same time keep
track of the original key. Note that the derivation function needn't be
(and generally won't be) bijective, otherwise it's too simple.

Therefore I propose adding the general pattern. Simple example:

   >>> d = transformdict(str.lower)
   >>> d['Foo'] = 5
   >>> d['foo']
   >>> d['FOO']
   >>> list(d)

(case-insensitive but case-preserving, as the best filesystems are ;-))

On the tracker issue, it seems everyone agreed on the principle. There
is some bikeshedding left to do, though. So here are the reasonable
naming proposals so far:

- transformkeydict
- coercekeydict
- transformdict
- coercedict

I have a sweet spot for "transformdict" myself.



More information about the Python-Dev mailing list