Batu Lab NotesPractical developer guides

Unpivot a fixed mapping into name-value rows

By Batu · English technical notes

Also published in our primary archive.

Unpivot a fixed mapping into name-value rows

To unpivot a fixed Python mapping into name-value rows, define the required field sequence and look up each value from it: [(name, dimensions[name]) for name in field_order]. This produces [('width', 3), ('height', 4)] even when the mapping was constructed in a different order.

The fixture intentionally inserts height before width, opposite the consumer's required width-first schema. The failing transformation, list(dimensions.items()), is non-mutating but emits insertion order, so it yields height first. That behavior is useful when insertion order is the intended contract, but it does not turn insertion history into a display, export, or positional schema.

The correction keeps field_order alongside the transformation and performs explicit dictionary lookups. The assertions distinguish the undesired iteration result from the required result, and confirm that neither transformation changed the input mapping. A direct lookup deliberately gives a KeyError if a required field is absent. For optional fields, choose and document a separate policy—such as omission, None, or rejection—rather than allowing iteration to decide it implicitly.

Python dictionaries preserve insertion order in Python 3.7 and later, which explains the failing result but does not select a domain-specific order. This example uses standard dictionary operations only. The Python documentation describes dictionaries and their insertion-order behavior in Mapping Types — dict.

AI assistance disclosure: this article was drafted with AI assistance, and its synthetic example was checked for deterministic output.

dimensions = {"height": 4, "width": 3}
original_dimensions = dimensions.copy()

# Failure: iteration follows insertion order, not the required schema order.
iterated_rows = list(dimensions.items())

# Correction: make the output schema explicit.
field_order = ("width", "height")
fixed_rows = [(name, dimensions[name]) for name in field_order]

assert dimensions == original_dimensions
assert iterated_rows == [("height", 4), ("width", 3)]
assert fixed_rows == [("width", 3), ("height", 4)]

print("input unchanged:", dimensions)
print("iteration rows:", iterated_rows)
print("fixed-order rows:", fixed_rows)
input unchanged: {'height': 4, 'width': 3}
iteration rows: [('height', 4), ('width', 3)]
fixed-order rows: [('width', 3), ('height', 4)]