Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
oorrja
GitHub Repository: oorrja/learntosolveit
Path: blob/master/languages/python/design_caseinsensitivedict.py
1240 views
1
#!/usr/bin/python
2
# $Id$
3
4
"""
5
Case Insenstive Dictionary Lookup. Dictionary keys are case sensitive. However
6
you might want some facilities to do a case-insenstive dictiionary lookup at
7
times. This provides the facility for the same.
8
"""
9
10
class CaseInsensitiveDict(dict):
11
def __init__(self, *args, **kwargs):
12
self._keystore = {}
13
d = dict(*args, **kwargs)
14
for k in list(d.keys()):
15
self._keystore[self._get_lower(k)] = k
16
return super(CaseInsensitiveDict,self).__init__(*args,**kwargs)
17
18
def __setitem__(self, k, v):
19
self._keystore[self._get_lower(k)] = k
20
return super(CaseInsensitiveDict, self).__setitem__(k, v)
21
22
def __getitem__(self, k):
23
return super(CaseInsensitiveDict,
24
self).__getitem__(self._keystore[self._get_lower(k)])
25
@staticmethod
26
def _get_lower(k):
27
if isinstance(k,str):
28
return k.lower()
29
else:
30
return k
31
32
def test():
33
obj = CaseInsensitiveDict([('name','senthil')])
34
print(obj)
35
obj['Sname']='kumaran'
36
obj['spam'] ='eggs'
37
obj['SPAM']='ham'
38
print(list(obj.items()))
39
obj1 = dict(fname='FIRST')
40
obj.update(obj1)
41
print(obj)
42
print(list(obj.keys()))
43
print(list(obj.items()))
44
print(obj['NAME'])
45
print(obj['SNAME'])
46
47
if __name__ == '__main__':
48
test()
49
50