Dev Helpers
← Back

Transpose a sparse row dictionary into columns

Transpose a sparse row dictionary into columns using Python lists and dictionaries.

Open this example in the interactive library

Source code

rows = {'a': {'x': 1}, 'b': {'x': 2, 'y': 3}}
columns = {}
for row, values in rows.items():
    for col, value in values.items():
        columns.setdefault(col, {})[row] = value
print(columns)

Sample output

{'x': {'a': 1, 'b': 2}, 'y': {'b': 3}}