Case-insensitive string compare?

Ethan Furman ethan at stoneleaf.us
Fri Sep 5 14:42:13 EDT 2008


Maric Michaud wrote:
> Le Friday 05 September 2008 14:33:22 J. Clifford Dyer, vous avez écrit :
> 
>>On Thu, 2008-09-04 at 18:48 -0500, Robert Dailey wrote:
>>
>>>Thanks everyone for your help. I'm not opposed to using [key.lower()
>>>for key in stage_map] at all, I was just curious to see if there were
>>>any cleaner alternatives. It looks like that is what I'll be using.
>>>I'm not familiar with how python works internally, but coming from C++
>>>it seems like "remaking" the map would be slow. However, speed is not
>>>my main concern in my particular situation, I'm just curious to learn
>>>more about python.
>>
>>You should be opposed to that particular solution.  You have just taken
>>a dictionary lookup (very fast) and turned it into a list traversal
>>(slow).  Even if speed isn't your main concern, this is an unnecessary
>>de-optimization.  You are deliberately slowing down your program to
>>avoid a slightly more verbose lookup later.  Your data structure might
>>as well be a list of tuples to begin with, to avoid creating a new list.
>>You have effectively made your keys useless as keys.
>>
>>If your lookups need to be case insensitive, make the key lower case,
>>and store the cased version in the value, whether as a tuple or a dict
>>(depending on whether you want named access).
>>
>>d = {
>>   'foo': {'key': 'Foo', 'value': 'val1'}
>>   'spam': {'key': 'sPAm', 'value': 'val2'}
>>}
>>
>>search = 'FOO'.lower()
>>if search in d:
>>    result = d[search]
>>    key = result['key']
>>    value = result['value']
>>
>>The only reason I wouldn't use this solution is if you expect to have
>>keys that will be identical when made lowercase, but if you're doing
>>case-insensitive lookup, you obviously don't expect this to be an issue.
> 
> The OP has already said the keys are case-sensitive, so this is not an option, 

Actually, the OP said:
-- So you're saying to ensure that stage_map's keys are initially
-- lower-case to begin with? Well, I can't do this either since the
-- *case of the keys is actually valuable* ***later on***. It's only for
-- the purposes of this specific comparison operation that the case
-- should be ignored.

In other words, the key (as a key) is case-insensitive, and the key (as 
a value) is case-sensitive -- making Clifford's comments and solution 
perfectly acceptable.

~Ethan~



More information about the Python-list mailing list