Python 想把字典写进excel。。。dict值是嵌套列表。。?
我有一本像这样的字典:Python 想把字典写进excel。。。dict值是嵌套列表。。?,python,python-3.x,python-2.7,pandas,openpyxl,Python,Python 3.x,Python 2.7,Pandas,Openpyxl,我有一本像这样的字典: res = {'err_1': [['ta1', 'ta2', 'ta3', 'ta4'], ['tc1', 'tc2', 'tc3', 'tc4'], ['2ta1', '2ta2', '2ta3'], ['2tc1', '2tc2', '2tc3']], 'err_2': [['2_ta1', '2_ta2', '2_ta3', '2_ta4'],
res = {'err_1': [['ta1', 'ta2', 'ta3', 'ta4'],
['tc1', 'tc2', 'tc3', 'tc4'],
['2ta1', '2ta2', '2ta3'],
['2tc1', '2tc2', '2tc3']],
'err_2': [['2_ta1', '2_ta2', '2_ta3', '2_ta4'],
['2_tc1', '2_tc2', '2_tc3', '2_tc4'],
['2_2ta1', '2_2ta2', '2_2ta3'],
['2_2tc1', '2_2tc2', '2_2tc3']]}
希望将其写入excel工作表。所以期望最终输出如下
err_1 ta1 tc1 2ta1 2tc1
ta2 tc2 2ta2 2tc2
ta3 tc3 2ta3 2tc3
ta4 tc4
err_2 2_ta1 2_tc1 2_2ta1 2_2tc1
2_ta2 2_tc2 2_2ta2 2_2tc2
2_ta3 2_tc3 2_2ta3 2_2tc3
2_ta4 2_tc4
尝试使用熊猫和其他动物也
df = pd.DataFrame.from_dict(res)
writer = pd.ExcelWriter('output.xlsx')
df.to_excel(writer, 'Sheet1', index_label=cl)
writer.save()
上面的代码在单个单元格中写入整个dict值。。我需要不同的细胞。。。
请帮助我们。。。提前感谢……您的第一个问题是,您希望dict res中的矩阵嵌套列表以转置形式写入。zip可用于转换嵌套列表;但是列表中缺少元素,也就是说,嵌套列表中的所有列表的长度都不相等。因此,我们可以使用itertools.zip_来填充缺失的元素
>>> from itertools import zip_longest
>>> res2 = {k: [*zip_longest(*l, fillvalue='')] for k,v in res.items()}
>>> res2
{'err_1': [('ta1', 'tc1', '2ta1', '2tc1'), ('ta2', 'tc2', '2ta2', '2tc2'), ('ta3', 'tc3', '2ta3', '2tc3'), ('ta4', 'tc4', '', '')], 'err_2': [('ta1', 'tc1', '2ta1', '2tc1'), ('ta2', 'tc2', '2ta2', '2tc2'), ('ta3', 'tc3', '2ta3', '2tc3'), ('ta4', 'tc4', '', '')]}
>>>
现在您可以将dict转换为DataFrame,如下所示
>>> import pandas as pd
>>> d = {r + str(c): res2[r][c] for r in res2 for c in range(len(res2[r]))}
>>> df = pd.DataFrame.from_dict(d, orient='index')
>>> df
0 1 2 3
err_10 ta1 tc1 2ta1 2tc1
err_11 ta2 tc2 2ta2 2tc2
err_12 ta3 tc3 2ta3 2tc3
err_13 ta4 tc4
err_20 ta1 tc1 2ta1 2tc1
err_21 ta2 tc2 2ta2 2tc2
err_22 ta3 tc3 2ta3 2tc3
err_23 ta4 tc4
>>>
最后,您可以将其写入excel文件,正如您已经提到的
>>> writer = pd.ExcelWriter('output.xlsx')
>>> df.to_excel(writer, 'Sheet1', index_label=False)
>>> writer.save()
Tq。。。我用xlwt得到了解决方案。。只需编写逻辑来循环所有值