Fix the assistant's field rename helper
Your task
Your team is moving user records to the v2 API, which renames several fields. You asked a coding assistant for a helper, and it wrote this:
def rename_fields(record, mapping):
for old, new in mapping.items():
if old in record:
record[new] = record.pop(old)
return record
Its tests pass, but every one of them renames a single field. Review the helper against the contract below, then write a corrected rename_fields(record, mapping).
The contract:
- Return a new dict and leave
recordunchanged. - Each key of
recordthat appears inmappingis renamed tomapping[key]. Keys not inmappingkeep their names. Values never change. A field name can be any string, even"constructor"or"toString". - All renames happen at once, each one read against the original keys.
{"a": "b", "b": "a"}swaps two fields, and{"a": "b", "b": "c"}movesatobandbtoc; it never turnsaintoc. - A mapping entry for a key the record does not have does nothing.
- If two fields of the record would end up with the same name, the helper must not silently drop one. Return
None(nullin JavaScript) instead, so the migration stops for that record.
Examples:
rename_fields({"fname": "Ada", "lname": "Lovelace", "id": 7}, {"fname": "first_name", "lname": "last_name"})returns{"first_name": "Ada", "last_name": "Lovelace", "id": 7}.rename_fields({"a": 1, "b": 2}, {"a": "b", "b": "a"})returns{"b": 1, "a": 2}. The assistant's version returns{"a": 1}: the second rename overwrote the value the first one had just moved.rename_fields({"email": "x@y.z", "mail": "old@y.z"}, {"mail": "email"})returnsNone: the renamedmailwould overwriteemail.
Examples
rename_fields(record: dict, mapping: dict[str, str]) -> dict | NoneExample 1
Input
rename_fields({"fname": "Ada", "lname": "Lovelace", "id": 7}, {"fname": "first_name", "lname": "last_name"})Output
{"first_name": "Ada", "last_name": "Lovelace", "id": 7}Example 2
Input
rename_fields({"a": 1, "b": 2}, {"a": "b", "b": "a"})Output
{"b": 1, "a": 2}Example 3
Input
rename_fields({"email": "x@y.z", "mail": "old@y.z"}, {"mail": "email"})Output
None