caseless dict - questions

Phoe6 orsenthil at gmail.com
Sat Jul 5 02:57:18 CEST 2008


I have a requirement for using caseless dict. I searched the web for
many different implementations and found one snippet which was
implemented in minimal and useful way.

#############
import UserDict

class CaseInsensitiveDict(dict, UserDict.DictMixin):
    def __init__(self, *args, **kwargs):
        self.orig = {}
        super(CaseInsensitiveDict, self).__init__(*args, **kwargs)
    def items(self):
        keys = dict.keys(self)
        values = dict.values(self)
        return [(self.orig[k],v) for k in keys for v in values]
    def __setitem__(self, k, v):
        hash_val = hash(k.lower())
        self.orig[hash_val] = k
        dict.__setitem__(self, hash_val, v)
    def __getitem__(self, k):
        return dict.__getitem__(self, hash(k.lower()))


obj = CaseInsensitiveDict()
obj['Name'] = 'senthil'
print obj
print obj.items()

obj1 = {}
obj1['Name'] = 'senthil'
print obj1
print obj1.items()
###########
[ors at goofy python]$ python cid1.py
{15034981: 'senthil'}
[('Name', 'senthil')]
{'Name': 'senthil'}
[('Name', 'senthil')]

---
The difference between the Caselessdict and {} is that when called as
the object, the Caselessdict() is giving me the internal
representation.
obj = CaseInsensitiveDict()
obj['Name'] = 'senthil'
print obj
gives: {15034981: 'senthil'}

obj1 = {}
obj1['Name'] = 'senthil'
print obj1
Correctly gives {'Name': 'senthil'}

What changes should I make to CaseInsensitiveDict ( written above), so
that its instance gives the actual dictionary instead of its internal
representation.
Constructing a dictionary and returning from __init__ method did not
work.

TIA,
Senthil





More information about the Python-list mailing list