Report keys present only on one side of two mappings
To report keys present only on one side of two Python mappings, compare their key sets with set difference. In the fixture, left has A and B while right has B and C, so the answer is left_only=['A'] and right_only=['C'].
The failed comparison looks at values. It reports no difference because both mappings happen to store the same value for their keys, even though each mapping has a different absent key. Values answer a different question: whether matched values differ. left.keys() and right.keys() expose dynamic views of the mappings’ keys; converting those views to sets makes the difference operation clear. Sorting the differences is not needed for membership, but it makes the printed output deterministic and easier to test. The correction creates new sets and lists and leaves both mappings unchanged.
The assertions verify this exact synthetic fixture and its input preservation. They do not decide whether a missing key should be an error, nor do they compare values for shared keys. Add a separate comparison for shared keys if that is required. Set difference is documented for Python set types, while the dictionary documentation describes mapping key views. This example uses established Python 3 APIs and has no special newer-version requirement.
AI assistance disclosure: This article was drafted with AI assistance and uses a synthetic, locally reproducible fixture.
Sources: Python set types and mapping types — dict.
left = {"A": "same", "B": "same"}
right = {"B": "same", "C": "same"}
original_left = left.copy()
original_right = right.copy()
# Failing question: values can match while keys are absent on each side.
value_difference = set(left.values()) - set(right.values())
assert value_difference == set()
left_only = sorted(set(left.keys()) - set(right.keys()))
right_only = sorted(set(right.keys()) - set(left.keys()))
assert left_only == ["A"]
assert right_only == ["C"]
assert left == original_left
assert right == original_right
print("left_only =", left_only)
print("right_only =", right_only)
left_only = ['A']
right_only = ['C']