S1Q3 · Add Average Key with Absolute Difference Value (In-Place)¶
⚡ Quick Reference
Function: add_average_key_diff(d: dict, k1, k2) -> None
Core idea: compute the average of the two keys (rounded) and the absolute difference of their values; insert as a new key-value pair.
def add_average_key_diff(d: dict, k1, k2) -> None:
new_key = round((k1 + k2) / 2)
new_value = abs(d[k1] - d[k2])
d[new_key] = new_value
Key rules:
- New key = round((k1 + k2) / 2) - stored as an int
- New value = abs(d[k1] - d[k2])
- Modify d in-place - return None
Problem Statement¶
Problem
Write a function add_average_key_diff(d, k1, k2) that inserts a new entry into dictionary d where the key is the rounded average of k1 and k2, and the value is the absolute difference of d[k1] and d[k2].
Example:
d={2: 10, 8: 30}, k1=2, k2=8
{2: 10, 8: 30, 5: 20}
new_key = round((2 + 8) / 2) = round(5.0) = 5
new_value = abs(10 - 30) = 20
d[5] = 20 → {2: 10, 8: 30, 5: 20} ✓
Solution approaches¶
Key takeaways¶
Average of keys - not values
The new key is the average of k1 and k2 (the dictionary keys themselves), not their values. The new value is the absolute difference of d[k1] and d[k2]. Don't mix them up.
Python's round() uses banker's rounding
round(2.5) = 2 and round(3.5) = 4 - Python rounds to the nearest even number on exact 0.5 cases. For most inputs this doesn't matter, but it's worth knowing when keys have an odd sum.
In-place - return None
d[new_key] = new_value modifies the original dictionary directly. The function returns nothing - the caller sees the change through their reference to d.