Python - Converting Dictionary into pandas dataframe

 



If you are having a dictionary with same set of sub keys for all the primary key's of your dict, then the below logic will help you in converting dictionary to pandas DataFrame

This logic works only for the format of dictionary shown below




import pandas as pd
dict_ = {'ABC College':{'courses':6,'students':500,'departments':7},'XYZ College':{'courses':5,'students':300,'departments':4}}
dict_
{'ABC College': {'courses': 6, 'students': 500, 'departments': 7}, 'XYZ College': {'courses': 5, 'students': 300, 'departments': 4}}

def converting_dict_into_df(dict_,main_key_name):
    ## INPUT the Column name for the KEY 'ABC','XYZ' frm the dict as college_name
    ## I m naming it as College Name . you can change based upon your case
    
    cols = [main_key_name]
    first_key = list(dict_.keys())[0]
    key_list = list(dict_[first_key].keys())
    cols.extend(key_list)
    df = {ele:[] for ele in cols}
    df[main_key_name].extend(list(dict_.keys()))
    for dn in df[main_key_name]:
        for k,v in dict_[dn].items():
            df[k].append(v)
    df_ = pd.DataFrame(df)
    return df_

key_name = 'college_name'
converting_dict_into_df(dict_,key_name)  

dict to dataframe, python , pandas, can we convert python dictionary to pandas dataframe Converting dictionary to dataframe, dict df conversion stackoverflow

No comments