I can use map to implement the case insensitive list search with Python.
a = ['xyz', 'wMa', 'Pma'];
b = map(string.lower, a)
if 'Xyz'.lower() in b:
print 'yes'
How can I do the same thing with dictionary?
I tried the following code, but ap has the list of [‘a’,’b’,’c’], not the case insensitive dictionary.
a = {'a':1, 'B':2, 'c':3}
ap = map(string.lower, a)
Note that making a dictionary case-insensitive, by whatever mean, may well lose information: for example, how would you “case-insensitivize”
{'a': 23, 'A': 45}?! If all you care is where a key is in the dict or not (i.e., don’t care about what value corresponds to it), then make asetinstead — i.e.(in every version of Python, or
{k.lower() for k in thedict}if you’re happy with your code working only in Python 2.7 or later for the sake of some purely decorative syntax sugar;-), and check withif k.lower() in theset: ....Or, you could make a wrapper class, e.g., maybe a read-only one…:
This will keep (without actually altering the original dictionary, so all precise information can still be retrieve for it, if and when needed) an arbitrary one of possibly-multiple values for keys that “collapse” into a single key due to the case-insensitiveness, and offer all read-only methods of dictionaries (with string keys, only) plus an
actual_key_casemethod returning the actual case mix used for any given string key (orNoneif no case-alteration of that given string key matches any key in the dictionary).