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:
1 2 3 4 5 |
my_dict = { "apple": 3, "banana": 5, "orange": 2 } |
To inspect this dictionary, simply print its contents:
1 |
print(my_dict) |
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:
1 2 3 4 |
if "apple" in my_dict: print("Apple found in the dictionary") else: print("Apple not found in the dictionary") |
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:
1 2 |
value = my_dict["apple"] print("Value of 'apple' in the dictionary:", value) |
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:
1 2 |
value = my_dict.get("apple", 0) print("Value of 'apple' in the dictionary:", value) |
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:
1 2 3 4 |
search_value = 5 for key, value in my_dict.items(): if value == search_value: print(f"Key with value {search_value}: {key}") |
Output:
Key with value 5: banana
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
my_dict = { "apple": 3, "banana": 5, "orange": 2 } print(my_dict) if "apple" in my_dict: print("Apple found in the dictionary") else: print("Apple not found in the dictionary") value = my_dict["apple"] print("Value of 'apple' in the dictionary:", value) value = my_dict.get("apple", 0) print("Value of 'apple' in the dictionary:", value) search_value = 5 for key, value in my_dict.items(): if value == search_value: print(f"Key with value {search_value}: {key}") |
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.