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
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:
result = {k: k * 2 for k in data}
print(result)
except Exception as e:
print(e)Output:
{'a': 'aa', 'b': 'bb'} 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}
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}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'}
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
adjusted_salaries = {
name: apply_bonus(sal)
for name, sal in salaries.items()
if sal < 100000
}
print(adjusted_salaries)Output:
{'John': 55000, 'Doe': 50000}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.