Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to search Python dictionary for matching key?
When working with Python dictionaries, you often need to search for keys in different ways. You can search for exact keys or find keys that match certain patterns or contain substrings.
Searching for Exact Keys
If you have the exact key you want to find, you can use the [] operator or get() method to retrieve the value associated with this key ?
student_grades = {
'alice': 85,
'bob': 92,
'charlie': 78
}
# Using [] operator
print(student_grades['alice'])
# Using get() method
print(student_grades.get('alice'))
85 85
Searching with Substring Matching
If you want to search for keys that contain a specific substring, you can iterate through the keys and use string methods like find() or in operator ?
Using find() Method
products = {
'laptop_dell': 899,
'laptop_hp': 750,
'mouse_wireless': 25,
'keyboard_mechanical': 120
}
for key in products.keys():
if key.find('laptop') > -1:
print(f"{key}: ${products[key]}")
laptop_dell: $899 laptop_hp: $750
Using 'in' Operator
products = {
'laptop_dell': 899,
'laptop_hp': 750,
'mouse_wireless': 25,
'keyboard_mechanical': 120
}
# More pythonic approach using 'in'
for key in products.keys():
if 'laptop' in key:
print(f"{key}: ${products[key]}")
laptop_dell: $899 laptop_hp: $750
Advanced Search Methods
Using List Comprehension
products = {
'laptop_dell': 899,
'laptop_hp': 750,
'mouse_wireless': 25,
'keyboard_mechanical': 120
}
# Find all keys containing 'key'
matching_items = {k: v for k, v in products.items() if 'key' in k}
print(matching_items)
{'keyboard_mechanical': 120}
Using Regular Expressions
import re
products = {
'laptop_dell': 899,
'laptop_hp': 750,
'mouse_wireless': 25,
'keyboard_mechanical': 120
}
# Find keys starting with 'laptop'
pattern = re.compile(r'^laptop')
matching_keys = [key for key in products.keys() if pattern.match(key)]
print(matching_keys)
['laptop_dell', 'laptop_hp']
Comparison
| Method | Use Case | Performance |
|---|---|---|
[] operator |
Exact key lookup | O(1) |
get() |
Safe exact key lookup | O(1) |
find() |
Substring search | O(n) |
in operator |
Substring search (pythonic) | O(n) |
| Regular expressions | Pattern matching | O(n) |
Conclusion
Use get() for safe exact key lookups and the in operator for substring searches. For complex pattern matching, regular expressions provide the most flexibility.
Advertisements
