You're seeing this error:
TypeError: 'int' object cannot be converted to 'PyString'
because you're trying to create a Polars DataFrame from a dictionary that contains another dictionary as a value, and that inner dictionary has non-string keys (in your case, the key 1 is an integer).
Polars (like many other data processing libraries) only supports serializable data structures in columns, and dictionary keys must be strings when treated as JSON-like objects.
❌ Problematic Code
import polars as pl
df = pl.DataFrame([{'a': {1: 2}}])
This structure is invalid to Polars because {1: 2} uses an integer key.
✅ Solution 1 – Convert inner dict keys to strings
If having a nested dictionary is truly what you want, you need to make sure your inner dict has string keys, like this:
import polars as pl
df = pl.DataFrame([{'a': {"1": 2}}]) # keys must be strings
print(df)
Output:
shape: (1, 1)
┌─────────────┐
│ a │
│ --- │
│ struct[1] │
╞═════════════╡
│ {1: 2} │
└─────────────┘
Alternatively, you'll see the value serialized as a JSON string if it can't be inferred as a struct.
✅ Solution 2 – If you meant to store JSON strings
Use json.dumps() to store the dictionary as a string column.
import polars as pl
import json
df = pl.DataFrame([
{'a': json.dumps({1: 2})} # turn it into a valid JSON string
])
print(df)
Output:
shape: (1, 1)
┌───────────┐
│ a │
│ --- │
│ str │
╞═══════════╡
│ {"1": 2} │
└───────────┘
Now column "a" is of type str, and it contains valid JSON.
✅ Solution 3 – Use structs, if appropriate
If you're trying to create complex/nested structures (like structs), you need to ensure types are explicitly supported.
df = pl.DataFrame([
{"a": pl.struct(dict(a=2, b=3))}
])
But note that Polars structs are explicitly typed and not the same as raw Python dictionaries.
🔚 Summary
| You want to store... | Do this... |
|---|