Case insensitive dictionary

后端 未结 10 2419
栀梦
栀梦 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:27

    If you only need to do this once in your code (hence, no point to a function), the most straightforward way to deal with the problem is this:

    lowercase_dict = {key.lower(): value for (key, value) in original_dict}

    I'm assuming here that the dict in question isn't all that large--it might be inelegant to duplicate it, but if it's not large, it isn't going to hurt anything.

    The advantage of this over @Fred's answer (though that also works) is that it produces the same result as a dict when the key isn't present: a KeyError.

提交回复
热议问题