convert a dictionary list to a dataframe

Use dict comprehension with flatten nested dicts and pass to Dataframe constructor:

df = pd.DataFrame({k: v for x in list_dict for k, v in x.items()})
print (df)
  test1 test2 test3
a     1     5   NaN
b    12    10   NaN
c    40    20   NaN
d   120   NaN   NaN
e    20   NaN    21
f     1   NaN    18
g     2   NaN    22
h     2   NaN    20

Or create DataFrame for each nested dictionary and pass to concat, if large dictionaries and many of outer keys this should be slowier like first solution:

df = pd.concat([pd.DataFrame(x) for x in list_dict], axis=1)
print (df)
  test1 test2 test3
a     1     5   NaN
b    12    10   NaN
c    40    20   NaN
d   120   NaN   NaN
e    20   NaN    21
f     1   NaN    18
g     2   NaN    22
h     2   NaN    20

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top