Junior
What are dictionary comprehensions in Python?
sobes.tech AI
Answer from AI
Dictionary comprehension — is a compact syntax for creating dictionaries based on an iterable object. It allows generating "key: value" pairs using expressions and optional filtering.
Syntax:
# basic syntax
dict = {key_expression: value_expression for item in iterable}
# with condition
dict = {key_expression: value_expression for item in iterable if condition}
Examples:
Creating a dictionary of squares of numbers from 0 to 4:
# dictionary where key is the number, value is its square
squares = {x: x**2 for x in range(5)}
# squares = {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Creating a dictionary only for even numbers:
# dictionary of squares of only even numbers
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
# even_squares = {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
Swapping keys and values:
original_dict = {'a': 1, 'b': 2, 'c': 3}
# dictionary with keys and values reversed
inverted_dict = {value: key for key, value in original_dict.items()}
# inverted_dict = {1: 'a', 2: 'b', 3: 'c'}
Advantages:
- Conciseness: More compact than equivalent
forloops. - Readability: Often clearer code for simple transformations.
- Efficiency: Can be slightly faster than
forloops in some cases.
Disadvantages:
- Readability for complex cases: Can become less readable for very complex logic.
- No side effects: Not intended for actions unrelated to dictionary creation (e.g., printing something).