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.

  • Open the IDLE text editor, which comes with the Python programming language. A blank new source code opens.

  • Declare a dictionary and add some values to it by writing something like this:

    phoneBook = {'Terrence':123, 'Timothy':456, 'Sasha': 789}

  • 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:

  • 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'])

  • Write an "else" clause that occurs if the key was not found in the dictionary:


  • Indent the line following the "else" statement and write the next line:

    print("Key not found. Try finding others.")

  • Execute the program by pressing the "F5" key. The output will be:

    Terrence was found in the dictionary. His phone number is: 123


Promoted By Zergnet



You May Also Like

  • How to Program a Python Remote Start

    Among the leaders in car security systems, Python also features remotes that offer keyless entry and remote-start transmitters. These remotes allow you...

  • How to Create a Dictionary in Python

    In the Python programming language, a dictionary is a data structure that maps unique keys to values. In other programming languages, however,...

  • How to Use the Break Statement in Python

    Control flow is a fundamental concept in programming. Programmers often create loops and test conditions which need to be escaped from early....

Related Searches

Is DIY in your DNA? Become part of our maker community.
Submit Your Work!