How to Map Dictionary Values with a Transformation Function in Python
Create a reusable function that applies a transformation to every value in a dictionary and returns a new dict.
Python code
13 linesdef transform_dict_values(d, func):
"""Apply a transformation function to every value in a dictionary."""
return {key: func(value) for key, value in d.items()}
if __name__ == "__main__":
original = {"a": 1, "b": 2, "c": 3}
doubled = transform_dict_values(original, lambda x: x * 2)
print(doubled)
names = {"first": "alice", "second": "bob"}
upper = transform_dict_values(names, str.upper)
print(upper)
Output
{'a': 2, 'b': 4, 'c': 6}
{'first': 'ALICE', 'second': 'BOB'}
How it works
The function uses a dictionary comprehension to iterate over d.items() and apply the func to each value in-place. Because dictionaries are mutable but we return a new dict, the original remains unchanged. The lambda in the first example multiplies each number by 2, while str.upper converts strings to uppercase in the second. This pattern keeps the transformation logic separate from the data, making it reusable and easy to test.
Common mistakes
- Mutating the original dictionary instead of returning a new one
- Forgetting to include the key in the new dictionary, losing structure
- Passing a function that expects a key instead of a value
Variations
- Use `{k: func(v) for k, v in d.items()}` directly instead of a helper
- Use `dict(map(lambda kv: (kv[0], func(kv[1])), d.items()))` for a functional style
Real-world use cases
- Normalizing user input fields (e.g., trimming whitespace or lowercasing emails) before saving to a database.
- Converting API response values to a different type, such as changing strings to integers in a settings dict.
- Applying a uniform transformation to configuration values, like scaling all timeout values by a factor.
Sponsored
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.