[Tutor] dictionary swittching

ibraheem umaru-mohammed iumarumo@eidosnet.co.uk
Tue, 14 May 2002 11:26:51 +0100


[Sharriff Aina wrote...]
-| hello!
-| can someone tell me how to create key dependant actions? I have a dictionary that varies in contents:
-| 
-| ## code snippet
-| 
-| selector = ['a', 'b', 'c']
-| 
-| x = {'a': 1245, 'b': 'hello, 'c': 4444}
-| 
-| if "a" in x:
-|   print 'test1'
-| elif 'b' in x:
-|   print 'test2'
-| elif 'c' in x:
-|   print 'test3'
-| 
-| this does not work, any ideas?
-| 
-| 
-| great thanks
-| 
-| 
-| Sharriff

This only works as if under python2.2, where the in operator now works
on dictionary objects, so:

	"key in dict" is now the same as "dict.has_key(key)"

So assume your code is for an earlier version of python, you can change
it to the following:

-- cut -- 
selector = ['a', 'b', 'c']
x = {'a': 1245, 'b': 'hello, 'c': 4444}
 
if "a" in x.keys():
   print 'test1'
 elif 'b' in x.keys():
   print 'test2'
 elif 'c' in x.keys():
   print 'test3'
-- cut --

or IMO, even better:

-- cut --
  selector = ['a', 'b', 'c']
  x = {'a': 1245, 'b': 'hello, 'c': 4444}

  if x.has_key('a'):
    print "test1"
  elif x.has_key('b'):
    print "test2"
  elif x.has_key('c'):
    print "test3"
-- cut --

HTH,

			--ibs.
-- 
			ibraheem umaru-mohammed
			   www.micromuse.com
			         --0--