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.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 14 views 0 copies

Python code

13 lines
Python 3.9+
def 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

stdout
{'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

  1. Use `{k: func(v) for k, v in d.items()}` directly instead of a helper
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.