[Tutor] if string contains dictionary key

Wesley J. Chun wesc@alpha.ece.ucsb.edu
Thu, 10 Aug 2000 12:47:02 -0700 (PDT)


    > From: Steve <stevel@softhome.net>
    > Date: Thu, 10 Aug 2000 15:21:09 -0400
    > 
    > I know I am missing something obvious, but I am having a difficult 
    > time trying to get this to work.
    > 
    > s = 'This string contains a CLR'
    > 
    > d = {'CLR ': 'CLEAR', 'CA': 'ACCEPT', 'CR': 'CALL REQUEST'}
    > 
    > if s has d.keys():
    >    do stuff


close.  one problem is that d.keys() will only return a list, i.e.
['CLR', 'CA', 'CR'] (assuming your key is 'CLR', not 'CLR ' as in
your example.

the other problem is that you are trying to find whether your key
is a *substring* of a string, not the string itself.  if 's' was
just 'CLR', then you could've used:
 
if d.has_key(s):
    do stuff

but that's not how you presented your problem.  we need to use
some form of string.find() (find, rfind, index, rindex, etc.) to
help you out, as in the example below using a loop.  you can also
take advantage of python's for-else statement with your application:

- - - - -
import string

for eachKey in d.keys():
    if string.find(s, eachKey):	    # or s.find(eachKey) in 1.6+
	# do stuff
else:
    print 'no keys found in string "s"'
- - - - -

the import of the string module and module function call are
antiquated with the new string methods in Python 1.6 and higher.

hope this helps!!

-wesley

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

"Core Python Programming", Prentice Hall PTR, TBP Fall 2000
    http://www.phptr.com/ptrbooks/ptr_0130260363.html

Python Books:   http://www.softpro.com/languages-python.html

wesley.j.chun :: wesc@alpha.ece.ucsb.edu
cyberweb.consulting :: silicon.valley, ca
http://www.roadkill.com/~wesc/cyberweb/