John Henry napisal(a):
> I believe the standard dictionary should be amened to allow the use of
> case insensitive keys - as an option.  I found some work done by others
> to do that at:
>
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/283455
>
> but the problem with that approach is that they lowercase the keys
> immediately when you create the dictionary and so the true identity of
> the key is lost.
>
> Of course, I can subclass it and save a copy of the "real" key but
> that's kind of messcy.
>
> In other words:
>
> If I have:
>
>     pets=caselessDict()
>
>     pets["Cat"] = 3
>     pets["Dog"] = 2
>
> I would like to see:
>
>    pets["cat"]  prints 3
>    pets["DOG"] prints 2
>
> but
>
>    print pets.keys()
>
> should print:
>
> "Cat", "Dog"
>
> not:
>
> "cat", "dog"

How about:

>>> class Dictstr(str):
...     def __hash__(self):
...             return str.__hash__(self.lower())
...     def __eq__(self,other):
...             return self.lower()==other.lower()
...
>>> class dictt(dict):
...     def __setitem__(self, key, value):
...             if isinstance(key, str):
...                     dict.__setitem__(self, Dictstr(key), value)
...             else:
...                     dict.__setitem__(self, key, value)
...     def __getitem__(self, key):
...             if isinstance(key, str):
...                     return dict.__getitem__(self, Dictstr(key))
...             else:
...                     return dict.__getitem__(self, key)
...
>>> d=dictt()
>>> d[1]=1
>>> d['Cat']='Cat'
>>> d['Dog']='Dog'
>>> d['dOg']
'Dog'
>>> d.keys()
[1, 'Dog', 'Cat']

Note that you would need to redefine also __init__, __contains__ and
other methods.

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to