Package parasol :: Module LikeDict
[hide private]
[frames] | no frames]

Source Code for Module parasol.LikeDict

 1   
 2  __author__ = "Charlie Taylor (charlietaylor@sourceforge.net)" 
 3  __version__ = " 1.0 " 
 4  __date__ = "Oct 21, 2005" 
 5  __copyright__ = "Copyright (c) 2009 Charlie Taylor" 
 6  __license__ = "BSD" 
 7   
8 -class LikeDict:
9 """ 10 Dictionary, that has case-insensitive keys. (see SQL LIKE command) 11 12 Keys are retained in their original form 13 when queried with .keys() or .items(). 14 15 Implementation: An internal dictionary maps lowercase 16 keys to (key,value) pairs. All key lookups are done 17 against the lowercase keys, but all methods that expose 18 keys to the user retrieve the original keys. 19 """ 20
21 - def __init__(self, dict=None):
22 """Create an empty dictionary, or update from 'dict'.""" 23 self._dict = {} 24 if dict: 25 self.update(dict)
26
27 - def __getitem__(self, key):
28 """Retrieve the value associated with 'key' (in any case).""" 29 k = key.lower() 30 return self._dict[k][1]
31
32 - def __setitem__(self, key, value):
33 """Associate 'value' with 'key'. If 'key' already exists, but 34 in different case, it will be replaced.""" 35 k = key.lower() 36 self._dict[k] = (key, value)
37
38 - def has_key(self, key):
39 """Case insensitive test wether 'key' exists.""" 40 k = key.lower() 41 return self._dict.has_key(k)
42
43 - def keys(self):
44 """List of keys in their original case.""" 45 return [v[0] for v in self._dict.values()]
46
47 - def values(self):
48 """List of values.""" 49 return [v[1] for v in self._dict.values()]
50
51 - def items(self):
52 """List of (key,value) pairs.""" 53 return self._dict.values()
54
55 - def get(self, key, default=None):
56 """Retrieve value associated with 'key' or return default value 57 if 'key' doesn't exist.""" 58 try: 59 return self[key] 60 except KeyError: 61 return default
62
63 - def setdefault(self, key, default):
64 """If 'key' doesn't exists, associate it with the 'default' value. 65 Return value associated with 'key'.""" 66 if not self.has_key(key): 67 self[key] = default 68 return self[key]
69
70 - def update(self, dict):
71 """Copy (key,value) pairs from 'dict'.""" 72 for k,v in dict.items(): 73 self[k] = v
74
75 - def __repr__(self):
76 """String representation of the dictionary.""" 77 items = ", ".join([("%r: %r" % (k,v)) for k,v in self.items()]) 78 return "{%s}" % items
79
80 - def __str__(self):
81 """String representation of the dictionary.""" 82 return repr(self)
83