How to Find a Key in a Dictionary in Python
The Python programming language contains many built-in methods for organizing data. One such method is the dictionary, which associates a certain value with a unique key. Fetching the value is done by inputting the necessary key. It is somewhat like looking up a word in a real dictionary -- the word is the key, and the definition is the value. The syntax for looking up keys in a dictionary is very simple, so you can start searching dictionaries with little background in programming or Python.
Instructions
-
-
1
Open the IDLE text editor, which comes with the Python programming language. A blank new source code opens.
-
2
Declare a dictionary and add some values to it by writing something like this:
phoneBook = {'Terrence':123, 'Timothy':456, 'Sasha': 789}
-
-
3
Search the dictionary for a key, like "Terrence," using the "in" keyword. This can be done inside an "if" statement as follows:
if 'Terrence' in phonebook:
-
4
Print a message out that reveals whether or not "Terrence" was found in the dictionary. Press the "Tab" key on the next line following the "if" statement and write this:
print("Terrence was found in the dictionary. His phone number is: " , phoneBook['Terrence'])
-
5
Write an "else" clause that occurs if the key was not found in the dictionary:
else:
-
6
Indent the line following the "else" statement and write the next line:
print("Key not found. Try finding others.")
-
7
Execute the program by pressing the "F5" key. The output will be:
Terrence was found in the dictionary. His phone number is: 123
-
1