How to Apply a Function to Items in a Python Dictionary
Transforming data within a dictionary is a common task in Python, whether you are sanitizing user inputs, performing calculations on dataset columns, or formatting strings. Unlike lists, dictionaries possess both keys and values, requiring specific techniques to apply functions efficiently.
This guide explores how to apply functions to dictionary items using Dictionary Comprehensions (the standard, Pythonic way) and the functional map() approach, while highlighting common pitfalls.
Method 1: Dictionary Comprehension (Recommended)
The most readable and efficient way to apply a function to dictionary values is using a Dictionary Comprehension. This creates a new dictionary with transformed items.
Applying a Function to Values
The syntax {k: func(v) for k, v in d.items()} iterates through key-value pairs and applies the logic to v.
prices = {'apple': 100, 'banana': 200, 'cherry': 300}
def calculate_tax(price):
return price * 1.15
# ✅ Solution: Apply function to values, keep keys the same
taxed_prices = {item: calculate_tax(price) for item, price in prices.items()}
print(f"Original: {prices}")
print(f"Taxed: {taxed_prices}")
Output:
Original: {'apple': 100, 'banana': 200, 'cherry': 300}
Taxed: {'apple': 114.99999999999999, 'banana': 229.99999999999997, 'cherry': 345.0}
Common Mistake: Iterating Over Keys Only
If you simply iterate over the dictionary (for x in dict), you only get keys.
data = {'a': 1, 'b': 2}
try:
# ⛔️ Incorrect: Iterating 'data' directly yields keys, not values
# This tries to multiply the key string 'a' * 2, not the value
result = {k: k * 2 for k in data}
print(result)
except Exception as e:
print(e)
Output:
{'a': 'aa', 'b': 'bb'}
# (This is valid Python, but likely not the mathematical operation intended)
Method 2: Using map() (Functional Approach)
You can use map() with a lambda function, but it is often less readable because map operates on the (key, value) tuple yielded by .items(). You must construct the tuple manually and cast it back to a dict.
prices = {'apple': 100, 'banana': 200}
# ✅ Solution: Using map() to apply logic
# Note: The lambda receives a tuple 'x', where x[0] is key, x[1] is value
mapped_prices = dict(map(lambda x: (x[0], x[1] * 0.5), prices.items()))
print(f"Discounted: {mapped_prices}")
Output:
Discounted: {'apple': 50.0, 'banana': 100.0}
Using map(func, my_dict) directly (without .items()) will only iterate over the keys, effectively discarding your values.
Advanced: Transforming Keys and Values Simultaneously
Comprehensions allow you to manipulate both the key and the value in a single pass. This is useful for standardizing data (e.g., lowercasing keys).
raw_data = {'Name': 'Alice', 'AGE': 25, 'Job': 'Developer'}
# ✅ Solution: Lowercase keys AND convert values to string
cleaned_data = {k.lower(): str(v) for k, v in raw_data.items()}
print(cleaned_data)
Output:
{'name': 'Alice', 'age': '25', 'job': 'Developer'}
Advanced: Conditional Application (Filtering)
You can combine transformation with filtering. For example, applying a function only if a specific condition is met.
salaries = {'John': 50000, 'Jane': 120000, 'Doe': 45000}
def apply_bonus(salary):
return salary + 5000
# ✅ Solution: Apply bonus ONLY if salary < 100,000
# Note: The 'if' at the end filters which items make it into the new dict
adjusted_salaries = {
name: apply_bonus(sal)
for name, sal in salaries.items()
if sal < 100000
}
print(adjusted_salaries)
Output:
{'John': 55000, 'Doe': 50000}
If you want to keep all items but apply the function conditionally (logic like if-else), place the condition on the value side:
{k: (func(v) if v < 10 else v) for k, v in d.items()}
Conclusion
To apply a function to items in a Python dictionary:
- Use Dictionary Comprehension (
{k: func(v) for k, v in d.items()}) as your default choice for readability and speed. - Use
map()only if you prefer functional programming styles or are processing iterators lazily. - Remember
.items(): Always iterate over.items()to access both keys and values; iterating over the dictionary directly only gives you keys.