Fix the assistant's field rename helper

Review the AI's codeEasy15 min

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 record unchanged.
  • Each key of record that appears in mapping is renamed to mapping[key]. Keys not in mapping keep 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"} moves a to b and b to c; it never turns a into c.
  • 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 (null in 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"}) returns None: the renamed mail would overwrite email.

Examples

rename_fields(record: dict, mapping: dict[str, str]) -> dict | None
Example 1
Inputrename_fields({"fname": "Ada", "lname": "Lovelace", "id": 7}, {"fname": "first_name", "lname": "last_name"})
Output{"first_name": "Ada", "last_name": "Lovelace", "id": 7}
Example 2
Inputrename_fields({"a": 1, "b": 2}, {"a": "b", "b": "a"})
Output{"b": 1, "a": 2}
Example 3
Inputrename_fields({"email": "x@y.z", "mail": "old@y.z"}, {"mail": "email"})
OutputNone