Home > Software engineering >  How to convert for-loop generated dictionaries list to dataframe in python
How to convert for-loop generated dictionaries list to dataframe in python

Time:06-30

for-loop generating multiple lists and each list having, multiple dictionaries with similar 'key' names and want to make similar 'key' names as column names and values should be assigned to the value column in the dataframe.

Eg:

The outcome of 1st for loop

[{'name':'kumar','job':'Plumber'},{'name':'Rajesh','job':'Painter']

The outcome of 2nd for loop

[{'name':'Jaslin','job':'Teacher'},{'name':'Ramu','job':'Engineer']


df:

    name    job
0   Kumar   Plumber
1   Rajesh  Painter
2   Jaslin  Teacher
3   Ramu    Engineer

I'm beginner how to convert for-loop generated list to dataframe.

CodePudding user response:

Just combine both lists and send it as a parameter to DataFrame

l1 = [{'name': 'kumar', 'job': 'Plumber'}, {'name': 'Rajesh', 'job': 'Painter'}]
l2 = [{'name': 'Jaslin', 'job': 'Teacher'}, {'name': 'Ramu', 'job': 'Engineer'}]
df = pd.DataFrame(l1   l2)

Output

     name       job
0   kumar   Plumber
1  Rajesh   Painter
2  Jaslin   Teacher
3    Ramu  Engineer
  • Related