Case insensitive dictionary

后端 未结 10 2444
栀梦
栀梦 2020-11-27 14:47

I\'d like my dictionary to be case insensitive.

I have this example code:

text = \"practice changing the color\"

words = {\'color\': \'colour\',
            


        
10条回答
  •  日久生厌
    2020-11-27 15:28

    I just set up a function to handle this:

    def setLCdict(d, k, v):
        k = k.lower()
        d[k] = v
        return d
    
    myDict = {}
    

    So instead of

    myDict['A'] = 1
    myDict['B'] = 2
    

    You can:

    myDict = setLCdict(myDict, 'A', 1)
    myDict = setLCdict(myDict, 'B', 2)
    

    You can then either lower case the value before looking it up or write a function to do so.

        def lookupLCdict(d, k):
            k = k.lower()
            return d[k]
    
        myVal = lookupLCdict(myDict, 'a')
    

    Probably not ideal if you want to do this globally but works well if its just a subset you wish to use it for.

提交回复
热议问题