[Tutor] Dictionaries

Martin A. Brown martin at linux-ip.net
Sun Jun 17 16:50:20 CEST 2012


Greetings,

 : I am having a problem with a small application I am writing. I 
 : have to have the user input the key, then have the program output 
 : the value associated with it. A way to inform the user that the 
 : key they entered is not in the dictionary or somefing would be 
 : nice also.

I would agree also with Emile--in the future, you will probably get 
a better answer if you are more specific in your question.  This one 
is a pretty easy question to answer and show you some samples for 
how to approach this with code snippets.

I will assume that userinput is a variable with the contents of 
interest that your user typed.  I will use the variable d to 
represent some dictionary (any dictionary).

  if userinput in d:
      print 'Found', userinput, 'in dictionary, value was', d[userinput]
  else:
      print 'No entry'

Depending on what else you are doing (besides printing), you might 
also look into the get() method of dictionaries:

  default = '<nonexistent>'
  string_to_print = d.get(userinput,default)
  print 'You typed %s.  The entry was %s.' % ( userinput, string_to_print)

These are pretty common usage patterns for dictionaries, so you 
might benefit from looking at the other sorts of things that you can 
do with dictionaries.

Good luck,

-Martin

-- 
Martin A. Brown
http://linux-ip.net/


More information about the Tutor mailing list