Kim Kim - 1 month ago 13
Python Question

Case insensitive dictionary

I'd like my dictionary to be case insensitive.

I have this example code:

text = "practice changing the color"

words = {'color': 'colour',
'practice': 'practise'}

def replace(words,text):

keys = words.keys()

for i in keys:
text= text.replace(i ,words[i])
return text

text = replace(words,text)

print text

Output = practise changing the colour

I'd like another string "practice changing the Color" (where 'Color' starts with a capital) to also give the same output.

I believe there is a general way to convert to lowercase using
but I'm not sure how to best integrate this into my existing code. (If this would be a reasonable, simple approach anyway).

jkp jkp

If I understand you correctly and you want a way to key dictionaries in a non case-sensitive fashion, one way would be to subclass dict and overload the setter / getter:

class CaseInsensitiveDict(dict):
    def __setitem__(self, key, value):
        super(CaseInsensitiveDict, self).__setitem__(key.lower(), value)

    def __getitem__(self, key):
        return super(CaseInsensitiveDict, self).__getitem__(key.lower())