Lookup Techniques
Basic Lookup Methods
get() Method
The get()
method provides a safe way to retrieve dictionary values:
user = {"name": "John", "age": 30}
## Safe retrieval with default value
name = user.get("name", "Unknown")
city = user.get("city", "Not specified")
Direct Key Access
## Direct access (raises KeyError if key doesn't exist)
try:
age = user["age"]
except KeyError:
print("Key not found")
Advanced Lookup Techniques
Dictionary Comprehensions
## Creating lookup dictionaries efficiently
numbers = [1, 2, 3, 4, 5]
squared = {x: x**2 for x in numbers}
Technique |
Time Complexity |
Use Case |
Direct Access |
O(1) |
Known keys |
get() Method |
O(1) |
Safe retrieval |
Comprehension |
O(n) |
Dynamic creation |
Complex Lookup Strategies
graph TD
A[Lookup Strategy] --> B{Key Exists?}
B -->|Yes| C[Return Value]
B -->|No| D{Default Action}
D --> E[Return Default]
D --> F[Raise Exception]
D --> G[Create New Entry]
Nested Dictionary Lookups
## Handling nested dictionaries
users = {
"user1": {"name": "Alice", "skills": ["Python", "SQL"]},
"user2": {"name": "Bob", "skills": ["JavaScript"]}
}
## Safe nested lookup
def get_user_skills(username):
return users.get(username, {}).get("skills", [])
Key Lookup Methods
keys() Method
## Check if key exists
if "name" in user.keys():
print("Name found")
items() Method
## Iterate through key-value pairs
for key, value in user.items():
print(f"{key}: {value}")
- Use
get()
for safe lookups
- Leverage dictionary comprehensions for dynamic creation
- Minimize nested lookups for better performance
By mastering these lookup techniques, you'll write more robust and efficient Python code with LabEx.