Skip to content

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:

Input
d={2: 10, 8: 30}, k1=2, k2=8
d after call
{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

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
def add_average_key_diff(d: dict, k1, k2) -> None:
    # Compute the average of the two keys
    avg_key = (k1 + k2) / 2
    new_key = round(avg_key)           # round to nearest int

    # Compute absolute difference of values
    new_value = abs(d[k1] - d[k2])

    # Insert in-place
    d[new_key] = new_value
def add_average_key_diff(d: dict, k1, k2) -> None:
    d[round((k1 + k2) / 2)] = abs(d[k1] - d[k2])
def add_average_key_diff(d: dict, k1, k2) -> None:
    avg_key  = lambda a, b: round((a + b) / 2)
    abs_diff = lambda a, b: abs(d[a] - d[b])
    d[avg_key(k1, k2)] = abs_diff(k1, k2)

Key takeaways

01

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.

02

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.

03

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.