Case insensitive dictionary?

Elbert Lev elbertlev at hotmail.com
Sat Jun 26 18:54:43 EDT 2004


Thanks!

In my case I know for sure, that keys are strings. So I fill the
dictionary with keys as they come to me from the source (preserve the
case). Once the dictionary is filled, it is a "READ ONLY" object. In
other words: there is no group operation writing it back to the source
and there is no reason to modify it.

Is there something wrong with this code:

class RegValuesDict(dict):
    def __init__(self):
        pass    
    def __getitem__(self, k):
        try:
            tmpk = k.strip().lower()
            for key in self.keys():
                if key.strip().lower() == tmpk:
                    return dict.__getitem__(self, key)
        except:
            pass
        return None
    def has_key(self, k):
        try:
            tmpk = k.strip().lower()
            for key in self.keys():
                if key.strip().lower() == tmpk:
                    return True
        except:
            pass
        return False
########

regdict = RegValuesDict()
regdict["keyname1"] = "value1"
regdict["keyname2"] = "value1"

val1 = regdict["keyName1"]
if val1 == None:
    print "Too bad"

or

if not regdict.has_key("keyName1"):
    print "Too bad"
else:
    val1 = regdict["keyName1"]

or

val1 = regdict.get("keyName1", "good value")

Doing this in such a way, I remove the need for trapping exceptions in
every line of the client code.

Again: is there something wrong with this approach?



More information about the Python-list mailing list