Skip to content

S1Q3 · Increment Dict Value with Max Limit

⚡ Quick Reference

Function: increment_value_with_max_limit(d, key, inc, limit) -> None

Core idea: add inc to d[key], cap at limit using min().

def increment_value_with_max_limit(d: dict, key: str, inc: int, limit: int):
    d[key] = min(d[key] + inc, limit)

Key rules: - Modifies d in-place - returns None - min(current + inc, limit) caps the result automatically - Works for any increment, including when result is below limit


Problem Statement

Problem

Write a function increment_value_with_max_limit(d, key, inc, limit) that increments d[key] by inc, but caps it at limit. Modifies in-place, returns None.

Examples:

Call
d={"x":5,"y":3,"z":5}, key="y", inc=5, limit=5
d after call
{"x": 5, "y": 5, "z": 5}

3 + 5 = 8 > 5 → capped at 5

Call
key="z", inc=5, limit=11
d["z"] after call
10

5 + 5 = 10 < 11 → no cap, stays 10


Solution approaches

def increment_value_with_max_limit(d: dict, key: str, inc: int, limit: int):
    d[key] = min(d[key] + inc, limit)
def increment_value_with_max_limit(d: dict, key: str, inc: int, limit: int):
    new_value = d[key] + inc
    if new_value > limit:
        d[key] = limit
    else:
        d[key] = new_value
def increment_value_with_max_limit(d: dict, key: str, inc: int, limit: int):
    d.__setitem__(key, min(d[key] + inc, limit))

dict.__setitem__(key, value) is the explicit form of d[key] = value. Used when you need assignment in a functional expression.


Key takeaways

01

min() as a natural cap

min(value, ceiling) enforces an upper bound. The mirror - max(value, floor) - enforces a lower bound. Combine: min(max(v, lo), hi) clamps to a range.

02

In-place dict modification

d[key] = new_value modifies the dict the caller passed in. No return needed. Always check whether a problem wants in-place modification or a new return value.

03

Two-step: compute then cap

Think of it as two separate operations: d[key] + inc (increment), then min(..., limit) (cap). Naming them separately in the explanatory approach makes debugging easier.