Create pandas datafram from string with key value pairs in Python

Viewed 30

I have a string like this:

"key=IAfpK, age=58, key=WNVdi, age=64, key=jp9zt, age=47"

How can I convert it to a table using pandas.

1 Answers

Assuming keys and ages are in order:

import pandas as pd
from collections import defaultdict

s = "key=IAfpK, age=58, key=WNVdi, age=64, key=jp9zt, age=47"

d = defaultdict(list)

for kv_pair in s.split(", "):
    key, value = kv_pair.split("=")
    d[key].append(value)

df = pd.DataFrame(d)
print(df)
Related