Dictionary Comprehensions
Creating dicts with comprehension syntax
Interview Relevant: Pythonic code
Dictionary Comprehensions
Create dictionaries with comprehension syntax.
Code Examples
Dictionary comprehension patterns.
python
1# Basic comprehension
2squares = {x: x**2 for x in range(5)}
3# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
4
5# With condition
6evens = {x: x**2 for x in range(10) if x % 2 == 0}
7
8# From two lists
9keys = ["a", "b", "c"]
10values = [1, 2, 3]
11d = {k: v for k, v in zip(keys, values)}
12
13# Swap keys and values
14original = {"a": 1, "b": 2}
15swapped = {v: k for k, v in original.items()}
16
17# Filter dictionary
18d = {"a": 1, "b": 2, "c": 3}
19filtered = {k: v for k, v in d.items() if v > 1}
20
21# Transform values
22upper = {k: v.upper() for k, v in {"a": "hello", "b": "world"}.items()}