Summary of three methods for pandas to convert dict into dataframe

enter: my_dict = {‘ I ‘: 1, ‘love’: 2, ‘you’: 3}

expected output: my_df

      0
i     1
love  2
you   3

If the key and value in the dictionary are one-to-one, then directly entering my_df = pd.DataFrame(my_dict) will give an error “ValueError: If using all scalar values, you must pass an index”.

solution:

1, use DataFrame to specify the dictionary index index

import pandas as pd

my_dict = {'i': 1, 'love': 2, 'you': 3}
my_df = pd.DataFrame(my_dict,index=[0]).T

print(my_df)

2. DataFrame

import pandas as pd

my_dict = {'i': 1, 'love': 2, 'you': 3}
my_list = [my_dict]
my_df = pd.DataFrame(my_list).T

print(my_df)

3, DataFrame. From_dict

specific parameters can refer to the website: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.from_dict.html

import pandas as pd

my_dict = {'i': 1, 'love': 2, 'you': 3}
my_df = pd.DataFrame.from_dict(my_dict, orient='index')

print(my_df)

output

      0
i     1
love  2
you   3

Read More: