Comprehensions and Default Handling
Two of the most powerful and “Pythonic” techniques for working with dictionaries are comprehensions for creating them concisely and default handling for managing missing keys gracefully. Mastering these will make your code cleaner, more readable, and more robust.
Dictionary Comprehensions: Building Dictionaries on the Fly
A dictionary comprehension is a compact and expressive way to create a dictionary from an existing iterable. It follows a simple, readable syntax:
{key_expression: value_expression for item in iterable if condition}
Basic Comprehension
The simplest form creates a key and value from each item in an iterable.
Pyground
Create a dictionary mapping numbers from 1 to 5 to their cubes.
Expected Output:
{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}
Output:
Graceful Handling of Missing Keys
Accessing a dictionary key that doesn’t exist raises a KeyError
, which can crash your program. Python provides elegant ways to handle this.
1. The in
Keyword
The safest and most readable way to check for a key’s existence before trying to access it.
Pyground
Check if the key 'banana' exists in a fruit inventory before printing its quantity.
Expected Output:
We are out of bananas.