[Tutor] Matching dictionary entries by partial key

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Fri Oct 7 06:35:13 CEST 2005

On Thu, 6 Oct 2005, William O'Higgins Witteman wrote:

> I'm trying to traverse a dictionary looking for partial matches of the
> key, and I'm not sure how.  Here's a sample dictionary:
> dict = {00001234 : value1, 20051234 : value2, 20071234 : value3}
> Here's what I'm trying to do:
> for key in dict:
>     if key == 0000???? or key == 2005????:
>         do something with dict[key]
> The challenge is that I only care about the first four digits of the key
> for the purpose of this match - is there a way to express this? I could
> probably create a wrapper dictionary using just the first four digits of
> the key as they key, and containing the original key:value pair as a
> list within it, but that seems cumbersome.

Hi William,

The dictionary (hashtable) data structure is really meant for exact key
match: it does not do partial keyword match well at all, and trying to
bend it to do so is going against its grain.

But using the first four digits as the key sounds right for your
application: from what you've told us so far, you're trying to express a
quick dictionary lookup using the first four digits as the key.

If we do take this route, doing this is not too bad, especially if we take
advantage of a dictionary's setdefault() method:

>>> words = 'this is a test of the emergency broadcast system'.split()
>>> words
['this', 'is', 'a', 'test', 'of', 'the', 'emergency', 'broadcast',
>>> d = {}
>>> for word in words:
...     d.setdefault(word[0], []).append(word)
>>> d
{'a': ['a'], 'b': ['broadcast'], 'e': ['emergency'], 'i': ['is'], 'o':
['of'], 's': ['system'], 't': ['this', 'test', 'the']}

But as Kent mentioned, though, perhaps the easiest thing to implement is a
simple linear scan across all your key-values, and not worry until we know
this is a performance hotspot.  *grin* It really depends on how many
entries we're searching against.

More information about the Tutor mailing list