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

huangapple go评论57阅读模式
英文:

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

问题

你可以尝试以下方法来实现你想要的Excel表格布局:

首先,将这些字典合并为一个列表,每个字典作为其中的一个元素。然后,使用Python中的pandas库来创建DataFrame。这里是一些示例代码:

import pandas as pd

dict_A = {
    'a': 'a',
    'b': 'b'
}

dict_B = {
    'x': 'x',
    'y': 'y',
    'z': 'z'
}

dict_C = {
    'a': 'a',
    'm': 'm',
    'z': 'z'
}

# 将字典放入列表
dict_list = [dict_A, dict_B, dict_C]

# 使用pandas创建DataFrame
df = pd.DataFrame(dict_list)

# 将DataFrame保存为Excel文件
df.to_excel('output.xlsx', index=False)

这将创建一个名为'output.xlsx'的Excel文件,其中每个字典的内容会以所需的布局显示在表格中。

英文:

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

答案1

得分: 0

您可以将所有数据附加到一个列表[[keys],[values],[keys],...],然后将其读取为DataFrame,这样列表的每个条目就会成为数据框中的单独行。然后,您可以将数据框转换为 Excel。

英文:

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)

huangapple
  • 本文由 发表于 2023年6月12日 17:15:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76455167.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定