Python dictionary comprehension is a compact, efficient, and effective method for creating dictionaries in Python.
Also It enables us to build dictionaries using a single line of code by iterating over an iterable object
Syntax
{key_expression: value_expression for item in iterable}
Features and Benefits
Compact Syntax: Allows creation of dictionaries in a single line, minimizing explicit loops and temporary variables.
Iterable Processing: Iterates over any iterable (e.g., lists, tuples, sets) to generate key-value pairs.
Expression Flexibility: Supports complex expressions for keys and values, including conditional statements for filtering or modification.
Readability: Enhances code clarity by succinctly expressing dictionary creation.
Nested Comprehensions: Permits nesting within other comprehensions, facilitating complex data transformations.
Efficiency: Optimized performance, typically faster than traditional loop and update methods.
Reduction in Code Length: Decreases lines of code compared to loop-based approaches for achieving the same outcome.
Declarative Programming: Promotes a declarative style where the focus is on defining outcomes rather than explicit iteration and conditions.
Suitability for Functional Programming: Harmonizes with functional programming principles, emphasizing expressions and immutability.
Example 1 Create a dictionary of squares of numbers from 1 to 5.
With Normal Loops
square_dict = {} for x in range(1, 6): square_dict[x] = x**2 print(square_dict) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
With Dictionary Comprehension
square_dict = {x: x**2 for x in range(1, 6)} print(square_dict) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Example 2: Create a dictionary of (letter, number) pairs from a list of letters
With Normal Loops
nested_dict = {} for letter in letters: for num in numbers: nested_dict[letter] = num print(nested_dict) # Output: {'a': 3, 'b': 3, 'c': 3}
With Dictionary Comprehension
letters = ['a', 'b', 'c'] numbers = range(1, 4) nested_dict = {letter: num for letter in letters for num in numbers} print(nested_dict) # Output: {'a': 3, 'b': 3, 'c': 3}
Example 3: with if-else condition
Create a dictionary where keys are numbers and values are their classification based on size.
With Normal Loops
size_dict = {} for num in numbers: if num < 30: size_dict[num] = 'small' elif num < 40: size_dict[num] = 'medium' else: size_dict[num] = 'large' print(size_dict) # Output: {10: 'small', 20: 'small', 30: 'medium', 40: 'large', 50: 'large'}
With Dictionary Comprehension
numbers = [10, 20, 30, 40, 50] size_dict = {num: ('small' if num < 30 else 'medium' if num < 40 else 'large') for num in numbers} print(size_dict) # Output: {10: 'small', 20: 'small', 30: 'medium', 40: 'large', 50: 'large'}
Example 4: with if-else condition
Create a dictionary with numbers as keys and their classification (even or odd) as values.
With Normal Loops
even_odd_dict = {} for num in numbers: if num % 2 == 0: even_odd_dict[num] = 'even' else: even_odd_dict[num] = 'odd' print(even_odd_dict) # Output: {1: 'odd', 2: 'even', 3: 'odd', 4: 'even', 5: 'odd'}
With Dictionary Comprehension
numbers = [1, 2, 3, 4, 5] even_odd_dict = {num: ('even' if num % 2 == 0 else 'odd') for num in numbers} print(even_odd_dict) # Output: {1: 'odd', 2: 'even', 3: 'odd', 4: 'even', 5: 'odd'}