Python Reference
Run Python examples for comparing dictionaries, producing stable JSON, and counting duplicate lines.
Run the examples
Save each example as example.py and run python3 example.py. The examples use the Python standard library.
Compare dictionary keys and values
Subtract the key views to find added or removed keys. Compare values only for keys present in both dictionaries, then sort all three lists so the result has a consistent order.
before = {"port": 80, "host": "localhost"}
after = {"port": 8080, "debug": False}
print("added:", sorted(after.keys() - before.keys()))
print("removed:", sorted(before.keys() - after.keys()))
changed = [key for key in before.keys() & after.keys() if before[key] != after[key]]
print("changed:", sorted(changed))Expected output
added: ['debug']
removed: ['host']
changed: ['port']Common mistake
Using get() on both dictionaries can conflate a missing key with a key whose value is None. Compare membership before comparing values.
Normalize JSON before a text diff
Parse the JSON, then serialize it with sorted object keys and consistent separators. This removes formatting differences while preserving array order.
import json
data = json.loads('{"port": 80, "host": "localhost"}')
print(json.dumps(data, sort_keys=True, separators=(",", ":"), ensure_ascii=False))Expected output
{"host":"localhost","port":80}Common mistake
The default decoder keeps the last value for duplicate object keys. Check for duplicate keys separately if that matters to your comparison.
Compare line counts with Counter
Counter subtraction keeps positive differences. Subtract in both directions to find excess lines in each input.
from collections import Counter
before = Counter(["apple", "apple", "pear"])
after = Counter(["apple", "pear", "pear"])
print("removed:", dict(before - after))
print("added:", dict(after - before))Expected output
removed: {'apple': 1}
added: {'pear': 1}Common mistake
A set drops duplicates. Use sets for membership and Counter for frequency. This comparison ignores line order.