esoteric question about dict keys (Re: age of Python programmers)

Jeff Epler jepler at unpythonic.net
Fri Aug 20 18:47:21 EDT 2004


There's no reason that the __getitem__ special method would not be
permitted to take a dict argument.

Many people will probably think that your use of Python's subscript
operator is a strange one, mostly because x[i] returns a single element
from x for lists, tuples, strings and dicts (the important built-in
subscriptable types), but your syntax will probably return multiple
rows.  In fact, this may be a problem of internal consistency, because
table[pkey_value] will presumably return a row object, not a sequence of
rows (or am I wrong about that, and you'll get a sequence of 1 row in
that case?)

Here's a program that uses dicts as arguments to the subscript operator.
"class Roda" takes a wordlist, and can either return the j'th word, or
all words with exactly N copies of some letter(s).

    class Roda:
        def __init__(self, wordlist):
            self.wordlist = wordlist

        def __getitem__(self, item):
            if isinstance(item, int): return self.wordlist[item]
            n = len(item)
            return [word for word in self.wordlist if len(
                        [None for (k, v) in item.items() if word.count(k) == v])==n]

    s = Roda(open("/usr/share/dict/words").read().split())
    print s[{'a': 3}][:10]         # first ten words with exactly 3 As
    print s[{'b': 2, 'c': 1}][:10] # first ten words with 2 Bs and 1 C
another problem this made me think of is that I don't see how to expand
this to "at least N", "at most N" or "from M to N" items, and likewise
for the kinds of query constraints you'd like to make (and can make in
SQL)

Well, anyway, if this really makes a big difference in the ease of
writing the code you need to write, and you're not too worried that
someone else who might maintain your code in the future won't be able to
understand it (documentation and comments would help here), then go
right ahead.

Jeff
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20040820/a54264d8/attachment.sig>


More information about the Python-list mailing list