Home > Software design >  Dict or DataFrame into excel matching keys and columns title
Dict or DataFrame into excel matching keys and columns title

Time:02-02

I want to add dictionaries or dataframes to excel based on the keys of the dict

dict1={'fruit':'apple','animal':'tiger'}
dict2={'fruit':['banana','mango'],'city':['Rio','Porto']}

to excel:

fruit animal city
apple tiger
banana rio
mango porto

without the keys if possible. If a key is not on the excel, it creates a new column. What would be a fast way to do it?

CodePudding user response:

Use pd.DataFrame.from_dict:

pd.concat([pd.DataFrame.from_dict(dict1, orient='index').T,
           pd.DataFrame.from_dict(dict2, orient='index').T],
          ignore_index=True).to_excel('output.xlsx', index=False)

enter image description here

  •  Tags:  
  • Related