Case-insensitive string compare?

J. Clifford Dyer jcd at
Fri Sep 5 14:33:22 CEST 2008

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.


More information about the Python-list mailing list