[Tutor] Dictionary Question
cs at zip.com.au
cs at zip.com.au
Mon May 2 21:35:43 EDT 2016
On 03May2016 00:56, Jason N. <nymcity at yahoo.com> wrote:
>Thank you all for your responses.
>A quick follow up, what is the best way to make dictionary requests case
>in-sensitive? For example, "Apple and "apple" should bring back the same
>dictionary response. Thank you.
There are a few ways depending what your more fine grained objectives are. But
they all tend to revolve around "normalising" the keys, which is a common
practice for many things where multiple values are considered the same: in your
case upper and lower case.
So the easy thing is to always convert to lower case (or upper case, but lower
case is less SHOUTY). Eg:
def save(d, key, value):
d[key.lower()] = value
so the normalising function here is d.lower.
Usually you'd be making yourself a mapping class of some kind: an object which
behaves like a dictionay:
https://docs.python.org/3/glossary.html#term-mapping
And internally it would usually have a dictionary for storage. Completely
untested example code:
class CaseInsensitiveMapping:
def __init__(self):
self._d = {}
def __getitem__(self, key):
return self._d[key.lower()]
def __setitem__(self, key, value):
self._d[key.lower()] = value
and so forth for the other special ("dunder" in Pythonspeak) methods used to
implement a mapping:
https://docs.python.org/3/reference/datamodel.html#emulating-container-types
From the outside:
cimap = CaseInsensitiveMapping()
cimap['X']=1
print(cimap['x'])
should print 1.
Now having sketched a trivial example like this, you might need to be more
elaborate depending on youruse case. For example, some mappings like this one
preserve the case used to insert the original key. So while ['X'] and ['x']
would both find the value 1, they .keys() method with recite 'X' because that
was the specific string used to put the 1 into the mapping. That would make the
internal implementation more complicated.
Cheers,
Cameron Simpson <cs at zip.com.au>
More information about the Tutor
mailing list