Dictionary Comprehensions
Dictionary comprehensions are a concise and efficient way to create dictionaries in Python. They allow you to generate dictionaries by applying an expression to each item in an iterable and specifying key-value pairs within a single line of code. This section covers the basics of dictionary comprehensions and demonstrates their usage.
1. Basic Dictionary Comprehension
The basic syntax of a dictionary comprehension consists of curly braces {}
enclosing a key-value expression followed by a for
clause.
# Create a dictionary of squares for numbers from 0 to 4
squares = {x: x ** 2 for x in range(5)}
In this example, the expression x ** 2
is applied to each item in the iterable range(5)
, generating key-value pairs where the key is x
and the value is the square of x
.
2. Dictionary Comprehension with Condition
You can include an optional condition in a dictionary comprehension to filter items from the source iterable.
# Create a dictionary of even squares for numbers from 0 to 9
even_squares = {x: x ** 2 for x in range(10) if x % 2 == 0}
In this example, the condition x % 2 == 0
filters out odd numbers, resulting in a dictionary of even squares.
3. Transforming Existing Dictionaries
You can use dictionary comprehensions to transform an existing dictionary by applying an expression to its key-value pairs.
# Transform an existing dictionary by squaring the values
original_dict = {'a': 1, 'b': 2, 'c': 3}
squared_values = {k: v ** 2 for k, v in original_dict.items()}
This example creates a new dictionary with the same keys and squared values based on the original dictionary.
4. Benefits of Dictionary Comprehensions
- Conciseness: Dictionary comprehensions provide a compact and readable way to create dictionaries.
- Efficiency: Dictionary comprehensions are optimized for speed and are faster than equivalent
for
loops. - Clarity: Dictionary comprehensions express the creation and transformation of dictionaries directly from data, making the code more understandable.
Dictionary comprehensions are a valuable feature in Python for creating dictionaries, transforming existing dictionaries, and filtering items efficiently. They simplify the code and improve readability.