Create polars dataframe from dict (with keys & values being their own columns)
07:45 31 Jul 2024

I have the following code

import polars as pl

mapping = {
    'CASH':  {'qty':  1, 'origin': 'E'},
    'ITEM':  {'qty': -9, 'origin': 'A'},
    'CHECK': {'qty': 46, 'origin': 'A'},
}

df = pl.DataFrame([{'type': k} | v for k, v in mapping.items()])\
         .with_columns(pl.struct(['qty', 'origin']).alias('mapping'))\
         .select(pl.col(['type', 'mapping']))

So the keys of the dict should become a new column called type and the values of the dict should be in their own mapping column. My above implementation works, and df looks like this:

shape: (3, 2)
┌───────┬───────────┐
│ type  ┆ mapping   │
│ ---   ┆ ---       │
│ str   ┆ struct[2] │
╞═══════╪═══════════╡
│ CASH  ┆ {1,"E"}   │
│ ITEM  ┆ {-9,"A"}  │
│ CHECK ┆ {46,"A"}  │
└───────┴───────────┘

But my implementation is very long and does not look very efficient. Is there a more idiomatic polars way to create this dataframe?

python dataframe dictionary python-polars