Search code examples
python-3.xdictionaryexport-to-excel

Is there a way to write multiple dictionaries with different keys to the same excel sheet using python?


I have multiple dictionaries with different keys in each dictionary. For eg,

dict A = {
    'a' = 'a',
    'b' = 'b'
}
dict B = {
    'x' = 'x',
    'y' = 'y',
    'z' = 'z'
}
dict C = {
    'a' = 'a',
    'm' = 'm',
    'z' = 'z'
}

Is there a way to write this into an excel sheet one below the other, something like:

a b
a b
x y z
x y z
a m z
a m z

I tried converting it into a list of dictionaries and creating a dataframe using pandas, but it adds all the keys of all dictionaries to the first row, something like:

a b x y z m

Solution

  • You can append all of your data to a list [[keys],[values],[keys],...] and then read it as a DataFrame, that way each entry of the list would be a separate row in the data frame. You can then convert the data frame to an excel.

    dict_list = []
    
    for dd in [dictA, dictB, dictC]:
        dict_list.append(list(dd.keys()))
        dict_list.append(list(dd.values()))
    
    
    df = pd.DataFrame(data=dict_list)
    
    df.to_excel('dict_data.xlsx', index=False, header=False)