Case-insensitive dict, non-destructive, fast, anyone?

Bengt Richter bokr at oz.net
Fri Apr 1 17:21:33 EST 2005


On Fri, 01 Apr 2005 18:52:00 GMT, "Raymond Hettinger" <vze4rx4y at verizon.net> wrote:

>[Ville Vainio]
>> I need a dict (well, it would be optimal anyway) class that stores the
>> keys as strings without coercing the case to upper or lower, but still
>> provides fast lookup (i.e. uses hash table).
>
>
>>>> class S(str):
>    def __hash__(self):
>        return hash(self.lower())
>    def __eq__(self, other):
>        return self.lower() == other.lower()
>
>
>>>> d = {}
>>>> d[S('ThE')] = 'quick'
>>>> d[S('the')]
>'quick'
>>>> d
>{'ThE': 'quick'}
>
Building on your S to sneak in a generalized idea ;-)

 >>> class idict(dict):
 ...     def __setitem__(self, key, value):
 ...         dict.__setitem__(self, S(key), value)
 ...     def __getitem__(self, key):
 ...         return dict.__getitem__(self, S(key))
 ...
 >>> d = idict()
 >>> d['ThE'] = 'quick'
 >>> d['the']
 'quick'
 >>> d
 {'ThE': 'quick'}

Ok, the idea:
I wonder if a dict with a general override hook for hashing all keys would be useful.
E.g.,  a dict.__keyhash__ that would take key as arg and default as now returning key.__hash__()
but that you could override. Seems like this could potentially be more efficient than key wrappers,
and would also make it so you wouldn't have to chase all the affected methods in doing an idict
like the above (e.g., get, setdefault, update etc. etc.)

Regards,
Bengt Richter



More information about the Python-list mailing list