S1Q3 · Swap the Last Chars in Dictionary Values¶
⚡ Quick Reference
Function: swap_last_chars_of_values(d: dict, k1, k2) -> None
Core idea: extract the last character of each value, swap them, rebuild both strings.
def swap_last_chars_of_values(d: dict, k1, k2):
v1, v2 = d[k1], d[k2]
d[k1] = v1[:-1] + v2[-1]
d[k2] = v2[:-1] + v1[-1]
Key rules:
- v[-1] → last character
- v[:-1] → everything except the last character
- Modifies the dict in-place - returns None
- Save both last chars before modifying (avoid overwriting)
Problem Statement¶
Problem
Write a function swap_last_chars_of_values(d, k1, k2) that swaps the last characters of the string values at keys k1 and k2 in dictionary d, modifying it in-place.
Examples:
d={"first":"apple","second":"mango","third":"banana"}, k1="first", k2="second"
{"first": "applo", "second": "mange", "third": "banana"}
d={"key1":"hello","key2":"world"}, k1="key1", k2="key2"
{"key1": "helld", "key2": "worlo"}
Tracing both examples¶
Example 1: d["first"] = "apple", d["second"] = "mango"
v1 = "apple", v2 = "mango"
v1[-1] = 'e', v2[-1] = 'o'
d["first"] = "appl" + "o" = "applo"
d["second"] = "mang" + "e" = "mange"
"third" is untouched ✓
Example 2: d["key1"] = "hello", d["key2"] = "world"
v1 = "hello", v2 = "world"
v1[-1] = 'o', v2[-1] = 'd'
d["key1"] = "hell" + "d" = "helld"
d["key2"] = "worl" + "o" = "worlo"
✓
Why save both values upfront?
If you updated d[k1] first and then read d[k1][-1] for the swap, you'd get the already-modified last character - not the original one. Always read both original values into local variables before writing back.
Solution approaches¶
def swap_last_chars_of_values(d: dict, k1, k2):
# Python evaluates the right side fully before assigning
d[k1], d[k2] = d[k1][:-1] + d[k2][-1], d[k2][:-1] + d[k1][-1]
Python evaluates the entire right-hand side before any assignment, so the original values of d[k1] and d[k2] are used in both expressions - no temporary variables needed.
Key takeaways¶
v[:-1] + new_char replaces the last character
v[:-1] slices everything except the last character. Concatenating a new character gives the modified string. This works for any string length since strings are immutable - you build a new one.
Read both values before writing either
Storing v1, v2 = d[k1], d[k2] before any modification ensures you use the original last characters for both swaps. Writing d[k1] first would corrupt the value needed for d[k2].
In-place modification - return None
The function modifies the dictionary directly and returns nothing. The caller sees the changes through the same dict reference. Don't return a new dict - that would leave the original unchanged.