Normalize a list of dict records by selected keys

Records from forms, JSON, or joined datasets often contain extra fields and inconsistent key sets. A small normalization step can project each input dictionary into the keys a downstream operation expects. Here the selected key order is ("id", "status", "owner"). For every record, the function creates a fresh dictionary in that order and uses None when a selected key is absent. Extra input keys, such as debug, are deliberately omitted.

The input list contains two synthetic records: the first lacks owner, and the second includes an extra debug field. The expected result therefore has the same three keys in both output dictionaries, with None for the first owner. The assertions verify the exact projection and that changing the normalized output does not mutate the original input record. That is useful because the code constructs new dictionaries, but it does not deep-copy values: a selected value that is itself a list or dictionary remains shared.

dict.get(key, default) supplies the explicit missing-value policy. Choose a different sentinel or reject missing fields when None is a valid business value. Dictionary operations used here are available in Python 3.2 and later, while this complete annotated example requires Python 3.9 or later because it uses list[dict] and tuple[str, ...]. See the official mapping types documentation for dictionary behavior and dict.get().

AI assistance disclosure: This article was drafted with AI assistance and should be reviewed in the context of its application.

import json


def normalize_records(records: list[dict], keys: tuple[str, ...]) -> list[dict]:
    return [{key: record.get(key) for key in keys} for record in records]


records = [
    {"id": 7, "status": "open"},
    {"id": 8, "status": "closed", "owner": "Mina", "debug": True},
]
normalized = normalize_records(records, ("id", "status", "owner"))

assert normalized == [
    {"id": 7, "status": "open", "owner": None},
    {"id": 8, "status": "closed", "owner": "Mina"},
]
normalized[0]["status"] = "changed"
assert records[0]["status"] == "open"

print(json.dumps(normalized, separators=(",", ":")))
[{"id":7,"status":"changed","owner":null},{"id":8,"status":"closed","owner":"Mina"}]

Comments

Popular posts from this blog

Compare Two Text Files in Python Without Modifying Them

Seven CSV Quality Checks to Run Before Importing Data

Explain why SQLite transactions cannot make an HTTP call atomic