[Tutor] Using re/search with dictionaries
Jackson
david.jay.jackson@wcox.com
Wed, 31 Oct 2001 20:25:40 -0700
Kirby --
Thanks for your reply. It fit the bill perfectly for what I need.
David
---------- Original Message ----------------------------------
From: Kirby Urner <urnerk@qwest.net>
Date: Wed, 31 Oct 2001 09:24:56 -0800
>
>Regular expressions search strings, not lists, so you
>can't use d.keys() as an arg to re.search() -- would have
>to do some conversion to/from to make this approach work.
>
>But regular expressions might be overkill if you're just
>wanting to find keys with embedded strings, nothing much
>fancier. Simpler string functions will do that job.
>
>Defining dictionary d as per your setup script, the
>function below lists all key/value pairs where the
>passed pattern (e.g. "blue") is found in the key:
>
> >>> def getmatches(pattern, thedict):
> keys = [i for i in thedict.keys() if i.find(pattern)>=0]
> for k in keys:
> print "%s = %s" % (k,thedict[k])
>
>
> >>> getmatches("blue",d)
> blue-003 = ['blueberry muffins']
> blue-002 = ['blueberry cobbler']
> blue-001 = ['blueberry pie']
> blueberry = ['muffins']
> bluebird = ['feathered friend']
>
>You could modify the above to work with regular expressions,
>but it'd search each key, one at a time. Again, if simple
>string functions will do the job, they're faster.
>
>Kirby
>
>At 10:04 AM 10/31/2001 -0700, Jackson wrote:
>>Greetings --
>>How do I search dict keys? and return the records that go along with them?
>>It seems as if it should be something along this line:
>>
>># we're looking for keys/records with blue* in them.
>>m=rd.search("\w[blue]+",d.keys())
>>if m: print repr(m.group(0))
>> and the output should be:
>>
>>[blue-001"]=["blueberry pie"]
>>["blue-002"]=["blueberry cobbler"]
>>["blue-003"]=["blueberry muffins"]
>>...
>>....
>>
>>
>>Thanks for you time
>>David Jackson
>
>
>_______________________________________________
>Tutor maillist - Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>