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????:

  if key.startswith('0000') or key.startswith('2005'):

or with a regular expresion:
  if re.match('0000|2005', key):

>         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.  Any one have a suggestion?

If you have a *lot* of keys and need more speed, that might be a good 
optimization. For a small dict, just use startswith().

Kent

> Thanks.
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to