grab dict keys/values without iterating ?!

Ian Kelly ian.g.kelly at gmail.com
Wed Dec 11 20:02:42 EST 2013


On Wed, Dec 11, 2013 at 7:30 AM, Tim Chase
<python.list at tim.thechases.com> wrote:
> On 2013-12-11 13:44, Steven D'Aprano wrote:
>> If necessary, I would consider having 26 dicts, one for each
>> initial letter:
>>
>> data = {}
>> for c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
>>     data[c] = {}
>>
>> then store keys in the particular dict. That way, if I wanted keys
>> starting with Aa, I would only search the A dict, not the B dict, C
>> dict, etc.
>
> That's what the convoluted code does that I put at the end of my
> previous post in this thread, only to the Nth degree (the outermost
> dict has the first letter which links to a dictionary of the 2nd
> level/letter, to the 3rd level/letter, etc).

This is what I did not so long ago when writing a utility for
typeahead lookup, except that to save some space and time I only
nested the dicts as deeply as there were still multiple entries.  As
an example of what the data structure looked like:

lookups = {
    'a': {
        'l': {
            'g': 'algebra',
            'p': 'alphanumeric',
        },
        's': 'asterisk',
    },
    'b': 'bobcat',
    ...
}

It does make the update process more complicated though, as adding new
words potentially requires existing words to be nested deeper than
they are currently.



More information about the Python-list mailing list