How To Search In A Dictionary In Python

Python provides a built-in data structure called a dictionary that allows you to store key-value pairs. Dictionaries are incredibly versatile and efficient – making them ideal for a wide range of applications. In this tutorial, we will learn how to effectively search a dictionary in Python.

Step 1: Create a Dictionary

First, let’s create a sample dictionary called “my_dict“. In this example, the dictionary comprises a few key-value pairs:

To inspect this dictionary, simply print its contents:

Output:

{'apple': 3, 'banana': 5, 'orange': 2}

Step 2: Check if a Key Exists in the Dictionary

To search for a specific key in the dictionary, use Python’s in keyword as shown below:

Output:

Apple found in the dictionary

Step 3: Access the Value of a Key

To access the value of a key in the dictionary, use square bracket notation:

Output:

Value of 'apple' in the dictionary: 3

In case the key is not present in the dictionary, the above method will throw a KeyError. You can prevent this by using the dict.get() method, which returns None by default, or a specified default value, if the key is not found:

Output:

Value of 'apple' in the dictionary: 3

Step 4: Iterate Over the Dictionary

To search for a value in a dictionary, iterate over its key-value pairs using a for loop and the dict.items() method:

Output:

Key with value 5: banana

Full Code

Conclusion

In this tutorial, we learned how to search a Python dictionary by validating a key’s existence, accessing key values, and iterating over keys and values. Python dictionaries prove useful in various applications, and this guide highlights the basics necessary to effectively search through them.