Three methods of converting dict into dataframe by pandas

Input: 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, enter my directly_ df = pd.DataFrame (my_ “Value error: if using all scalar values, you must pass an index”.

 

The solution is as follows:

1. Specifies the index of the dictionary when using the dataframe function

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. Convert dictionary dict to list and transfer it to 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. Use DataFrame.from_ Dict function

For specific parameters, please refer to the official 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 results

      0
i     1
love  2
you   3

Read More: