python - 将包含列表值的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
解决方案
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
推荐阅读
- c - C LinkedList 指针不适用于动态分配的数组
- swift - 如何扩展二维数组?
- java - 如何更改硒列表中的值
- android - 如何修复 kotlin 语言中的 PARSE_FAILED_MANIFEST_MALFORMED 错误?
- go - 如何遍历 c 数组
- vue.js - this.$children 表现得好像是被动的
- python - Pandas - 创建列,其中包含其他两列中存在的开始和结束年份之间的所有年份的列表
- r - R:创建具有节点属性的“statnet”网络
- mysql - 将 Oracle DB 数据迁移到 Mysql db
- python - 对形状不一致的数据执行 UMAP 降维 - python