首页 > 解决方案 > 将包含列表值的python字典导出到Excel工作表中

问题描述

下面是我的示例字典。

dict1 = {'X':[['a','1'], ['b','3'], ['c','2']],
         'Y':[['a','8'], ['b','13']],
         'Z':[['a','5'], ['b','7'], ['f','8']]}

我正在尝试使用 xlwt 模块在 excel 表中获取以下输出。

X    a       1
     b       3
     c       2

Y    a       8
     b      13

Z    a       5
     b       7
     f       8

标签: pythondictionaryxlwt

解决方案


dict1将键/值写入 excel 文件时不会保留其顺序,但一种选择可能是将内容放在OrderedDict中,然后将每个条目写入 excel 文件中的行、列:

import collections
# save order in dict1 to OrderedDict 
od = collections.OrderedDict(sorted(d.items(), key=lambda t: t[0]))

row = 0
for key in od.iterkeys():
    # write the key
    sheet.write(row, 0, key)
    for values in od[key]:
        for column, value in enumerate(values):
        # write each of this key's values in this row's columns    
        sheet.write(row, column+1, value)
        row += 1

除了键之间的空白行之外,它似乎与您想要的输出相匹配: 在此处输入图像描述


推荐阅读