Basic syntax
Pattern: {key: value for item in iterable}
# Create dict from list:
numbers = [1, 2, 3, 4, 5]
squares = {x: x ** 2 for x in numbers}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
From two lists
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
# Create dict mapping names to ages:
people = {name: age for name, age in zip(names, ages)}
print(people) # {'Alice': 25, 'Bob': 30, 'Charlie': 35}
With conditions
numbers = [1, 2, 3, 4, 5, 6]
# Only even numbers:
evens_dict = {x: x * 2 for x in numbers if x % 2 == 0}
print(evens_dict) # {2: 4, 4: 8, 6: 12}
Transform existing dict
original = {'a': 1, 'b': 2, 'c': 3}
# Double all values:
doubled = {k: v * 2 for k, v in original.items()}
print(doubled) # {'a': 2, 'b': 4, 'c': 6}
When to use
- Creating dictionaries from sequences
- Transforming existing dictionaries
- Filtering dictionary items
- More readable than loops for simple cases