Case insensitive dictionary

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

    You can do a dict key case insensitive search with a one liner:

    >>> input_dict = {'aBc':1, 'xyZ':2}
    >>> search_string = 'ABC'
    >>> next((value for key, value in input_dict.items() if key.lower()==search_string.lower()), None)
    1
    >>> search_string = 'EFG'
    >>> next((value for key, value in input_dict.items() if key.lower()==search_string.lower()), None)
    >>>
    
    

    You can place that into a function:

    
    def get_case_insensitive_key_value(input_dict, key):
        return next((value for dict_key, value in input_dict.items() if dict_key.lower() == key.lower()), None)
    
    
    

    Note that only the first match is returned.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-27 15:35

    Would you consider using string.lower() on your inputs and using a fully lowercase dictionary? It's a bit of a hacky solution, but it works

    0 讨论(0)
提交回复
热议问题