Dictionaries (dict) are key-value mappings implemented via high-performance hash tables. Since Python 3.7+, dictionaries preserve key insertion order while maintaining $O(1)$ average time complexity for lookups, insertions, and deletions.
flowchart LR
subgraph Keys (Must Be Hashable)
k1["'user_id'"]
k2["'role'"]
end
subgraph Hash Engine
h1["hash('user_id') -> 8742"]
h2["hash('role') -> 1290"]
end
subgraph Value Array
v1["10045"]
v2["'administrator'"]
end
k1 --> h1 --> v1
k2 --> h2 --> v2
dict[key]: Direct access. Raises KeyError if key is missing.dict.get(key, default): Safe access. Returns default (or None) if key is missing.dict.setdefault(key, default): Returns key value; inserts key: default if key is not present.dict.items(), dict.keys(), dict.values(): Dynamic view objects.from typing import Dict, Any
def process_user_metrics(logs: list[dict]) -> Dict[str, int]:
"""Aggregate request counts per endpoint using dictionary comprehension and get()."""
endpoint_counts: Dict[str, int] = {}
for log in logs:
endpoint = log.get("path", "/unknown")
# Increment counter safely
endpoint_counts[endpoint] = endpoint_counts.get(endpoint, 0) + 1
return endpoint_counts
if __name__ == "__main__":
sample_logs = [
{"path": "/api/v1/users", "status": 200},
{"path": "/api/v1/posts", "status": 200},
{"path": "/api/v1/users", "status": 200},
{"path": "/home", "status": 200},
]
metrics = process_user_metrics(sample_logs)
print("Endpoint Metrics:", metrics)
# Dictionary Unpacking (Merging in Python 3.9+)
default_config = {"theme": "dark", "notifications": True, "timeout": 30}
custom_config = {"timeout": 60, "language": "en"}
merged_config = default_config | custom_config # Merging operator '|'
print("Merged Configuration:", merged_config)
.get() for Optional Keys: Avoid triggering unhandled KeyError exceptions when reading optional dictionary fields.|): In Python 3.9+, merge two dictionaries cleanly with dict1 | dict2.Write a function invert_dict(d: dict) -> dict that swaps keys and values in a dictionary assuming all values are unique and hashable.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
You've completed this section! Take a quick 5-question quiz to check your understanding.