|
Package parasol ::
Module 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
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
22 """Create an empty dictionary, or update from 'dict'."""
23 self._dict = {}
24 if dict:
25 self.update(dict)
26
28 """Retrieve the value associated with 'key' (in any case)."""
29 k = key.lower()
30 return self._dict[k][1]
31
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
39 """Case insensitive test wether 'key' exists."""
40 k = key.lower()
41 return self._dict.has_key(k)
42
44 """List of keys in their original case."""
45 return [v[0] for v in self._dict.values()]
46
48 """List of values."""
49 return [v[1] for v in self._dict.values()]
50
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
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
71 """Copy (key,value) pairs from 'dict'."""
72 for k,v in dict.items():
73 self[k] = v
74
76 """String representation of the dictionary."""
77 items = ", ".join([("%r: %r" % (k,v)) for k,v in self.items()])
78 return "{%s}" % items
79
81 """String representation of the dictionary."""
82 return repr(self)
83