Apply a whitelist of allowed mapping fields
Also published in our primary archive.
To apply a whitelist of allowed mapping fields in Python, build a new dictionary from the allowed names instead of copying the whole record. The synthetic input contains id, name, and a token; the whitelist contains only id and name. The corrected result is therefore {'id': 'A', 'name': 'Item'}.
The failing transformation, record.copy(), is non-mutating but still copies every field. That means token reaches the output, which violates the stated selection rule. The dictionary comprehension makes the selection visible at the point where the output is made. This version includes an allowed field only when it is actually present, so it also handles a partial input without raising KeyError. If missing allowed fields must be rejected instead, remove the if field in record condition and let the direct lookup make that contract explicit.
The assertions prove the literal fixture omits token, preserves record, and returns the expected two-field mapping. They do not sanitize values, redact nested objects, or provide access control; a whitelist is only a data-shaping rule. The Python mapping documentation covers dictionaries and their key-based access. This code needs no API introduced in a recent Python release; it works on supported Python 3 versions.
AI assistance disclosure: This article was drafted with AI assistance and uses a synthetic, locally reproducible fixture.
Source: Python mapping types — dict.
record = {"id": "A", "name": "Item", "token": "secret"}
allowed = ("id", "name")
original_record = record.copy()
# Failing transformation: copying retains every field, including token.
leaked = record.copy()
assert "token" in leaked
selected = {field: record[field] for field in allowed if field in record}
expected = {"id": "A", "name": "Item"}
assert selected == expected
assert "token" not in selected
assert record == original_record
print("input:", record)
print("selected:", selected)
input: {'id': 'A', 'name': 'Item', 'token': 'secret'}
selected: {'id': 'A', 'name': 'Item'}