user2246905 user2246905 - 9 months ago 40
Python Question

List of dictionaries into dataframe python

I created some lists from some data and put them in the following way:

mylist1 =[{'vote1':{'john':'Y','peter':'Y'}}]
mylist2 =[{'vote2':{'john':'N','peter':'Y', 'david':'N'}}]

I want to create a dataframe from this so that it should be like this:

Name vote1 vote2
john Y N
peter Y Y
david NaN N

I tried with


but of course is not working. How could I do that?

Also I could rearrange the lists in a different form (since I´m creating them) if that would make things easier. However I´m creating the list and extending it inside a long loop, so I couldn't know all the names ex ante, the new names just would start appearing in the loop.

Answer Source

You're better off making just one dict of dicts:

In [5]: d = {'vote1': {'john': 'Y', 'peter': 'Y'}, 'vote2': {'john':'N','peter':'Y', 'david':'N'}}

In [6]: pd.DataFrame.from_dict(d)
      vote1 vote2
david   NaN     N
john      Y     N
peter     Y     Y