I am trying to add data to a python dataframe from multiple dictionary items, then operate on that data within the dataframe.

Here is my code below with the desired outcome:

import numpy as np import pandas as pd from numpy.random import randn mylist = [('Jane', 20), ('Helen', 30), ('Jack', 40)] mydict_one = {'Jane' : 10, 'Helen' : 15, 'Jack' : 20} mydict_two = {'Jane' : 30, 'Helen' : 45, 'Jack' : 60} df = pd.DataFrame([], [items[0] for items in mylist], ['mydict_one', 'mydict_two', 'subtracted_value']) print(df)

The desired outcome after adding the data would be as such:

mydict_one mydict_two subtracted_value Jane 10 30 20 Helen 15 45 30 Jack 20 60 40

I hope my question is clear enough.

## Answer

We can convert `mylist`

to a `dict`

, build the `DataFrame`

and `transpose`

:

df = pd.DataFrame( [mydict_one, mydict_two, dict(mylist)], index=['mydict_one', 'mydict_two', 'subtracted_value'] # "Column names" ).T # Transpose

`df`

:

mydict_one mydict_two subtracted_value Jane 10 30 20 Helen 15 45 30 Jack 20 60 40

We can also calculate subtracted value instead of using `mylist`

:

df = pd.DataFrame( [mydict_one, mydict_two], index=['mydict_one', 'mydict_two'] # "Column names" ).T # Transpose df['subtracted_value'] = df['mydict_two'] - df['mydict_one']

`df`

:

mydict_one mydict_two subtracted_value Jane 10 30 20 Helen 15 45 30 Jack 20 60 40