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

Daniel Dittmar daniel.dittmar at sap.corp
Fri Apr 1 13:01:11 CEST 2005


Ville Vainio wrote:
> 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).

Store the original key together with the value and use a lowercase key 
for lookup.

only a sketch:

class MyDict:
     def __init__ (self):
         self.inner = {}

     def __setitem__ (self, key, value):
         self.inner [key.lower ()] = (key, value]

     def __getitem__ (self, key):
         realkey, realvalue = self.inner [self]
         return realvalue

     def get (self, key, default = None):
         try:
             return self [key]
         except KeyError:
             return default
         # or: return self.inner.get (key.lower (), (None, default)) [1]

     def keys (self):
         return [realkey for realkey, realval in self.inner.values ()]

     def values (self):
         return [realval for realkey, realval in self.inner.values  )]

    def items ():
         return self.inner.values ()

     # iterators are left as an exercise



More information about the Python-list mailing list