Skip to main content

How to Apply a Function to Each Value in Python Dictionary

Data transformation is a core task in Python programming. You often need to modify every value in a dictionary, such as converting currency, formatting strings, or cleaning user input, while keeping the keys intact. Unlike lists, which are easily mapped, dictionaries require specific techniques to handle key-value pairs efficiently.

This guide explores the most effective methods to apply a function to dictionary values, focusing on readability and performance.

Understanding Dictionary Mapping

When you apply a function to a dictionary, your goal is typically to transform the values (v) while preserving the keys (k).

  • Input: {A: 10, B: 20}
  • Function: f(x) = x * 2
  • Output: {A: 20, B: 40}

There are two main approaches: creating a new dictionary (non-destructive) or modifying the existing dictionary in place. Creating a new dictionary is generally preferred to avoid side effects.

The most "Pythonic" and readable way to transform dictionary values is using dictionary comprehension. This syntax allows you to iterate over items and apply a function in a single, expressive line.

Syntax:

new_dict = {key: func(value) for key, value in original_dict.items()}

Example: Normalizing String Data

Suppose you have raw user data with inconsistent capitalization, and you want to standardize it.

raw_data = {
"name": "john doe",
"city": "new york",
"role": "admin"
}

# ✅ Correct: Apply .title() to every value using comprehension
cleaned_data = {k: v.title() for k, v in raw_data.items()}

print(f"Original: {raw_data}")
print(f"Cleaned: {cleaned_data}")

Output:

Original: {'name': 'john doe', 'city': 'new york', 'role': 'admin'}
Cleaned: {'name': 'John Doe', 'city': 'New York', 'role': 'Admin'}
tip

This method is preferred because it is explicit. You can clearly see that k (key) remains unchanged while v (value) is transformed.

Method 2: Using map() (Functional Approach)

If you prefer functional programming patterns, you can use map(). However, since map() operates on iterables, you must process the .items() tuple and then cast the result back to a dict. This is generally less readable than comprehension but useful in specific functional pipelines.

prices = {'apple': 1.50, 'banana': 0.80, 'cherry': 2.00}

def apply_tax(item_tuple):
key, price = item_tuple
# Increase price by 10%
return (key, round(price * 1.10, 2))

# ✅ Correct: Map the function over items, then convert back to dict
prices_with_tax = dict(map(apply_tax, prices.items()))

print(prices_with_tax)

Output:

{'apple': 1.65, 'banana': 0.88, 'cherry': 2.2}

Handling Errors: Mixed Data Types

A common issue arises when applying a function that expects a specific data type (like a string method) to a dictionary containing mixed types (e.g., strings and integers). This results in an AttributeError or TypeError.

Error Scenario

user_profile = {
"username": "alice",
"id": 1045, # Integer
"active": True # Boolean
}

try:
# ⛔️ Incorrect: Trying to call .upper() on all values, including int and bool
upper_profile = {k: v.upper() for k, v in user_profile.items()}
print(upper_profile)
except AttributeError as e:
print(f"Error: {e}")

Output:

Error: 'int' object has no attribute 'upper'

Solution: Conditional Logic

You should add a check inside your loop or function to handle different data types gracefully.

user_profile = {
"username": "alice",
"id": 1045,
"active": True
}

# ✅ Correct: Check if the value is a string before applying .upper()
safe_profile = {
k: (v.upper() if isinstance(v, str) else v)
for k, v in user_profile.items()
}

print(safe_profile)

Output:

{'username': 'ALICE', 'id': 1045, 'active': True}
note

If the transformation logic is complex, consider defining a separate helper function (e.g., def transform_value(v): ...) and calling that within the comprehension instead of writing inline if-else statements.

Conclusion

To apply a function to every value in a Python dictionary:

  1. Use Dictionary Comprehension ({k: f(v) for k, v in d.items()}) for the cleanest, most efficient code.
  2. Use map() only if you strictly follow functional programming paradigms, as it is less readable.
  3. Handle Data Types: Ensure your function can handle every type of value present in the dictionary, or use conditional logic (isinstance) to skip incompatible values.