将列表作为值的字典导出到Excel电子表格中

问题描述 投票:0回答:1

这是我的字典:{'MASS': ['RID39466', 'RID39056', 'RID3874'], 'RIGHT LOWER LOBE': ['RID1315'], 'RIGHT': ['RID5825'], 'LOWER': ['RID46058'], 'LOBE': ['RID5967'], 'LUNG': ['RID1301']}

我如何将此字典写到Excel电子表格中,以使只有两列?它应该看起来像这样:

|Text             | RID                       | 
|——————————————————————————————————————————————
|MASS             |RID39466, RID39056, RID3874|
|RIGHT LOWER LOBE |RID 1315                   |
|RIGHT            |RID5825                    |
 .
 .
 .

这是我的代码:

import openpyxl

annDict = {'MASS': ['RID39466', 'RID39056', 'RID3874'], 'RIGHT LOWER LOBE': ['RID1315'], 'RIGHT': ['RID5825'], 'LOWER': ['RID46058'], 'LOBE': ['RID5967'], 'LUNG': ['RID1301']}

row = 1
    for key,values in annDict.items():
        # Put the key in the first column for each key in the dictionary
        sheet.cell(row=row, column=1, value=key)
        sheet.cell(row=row, column=2, value=values)
        row += 1

    workbook.save(filename="my_workbook.xlsx")

[执行此操作时,出现ValueError提示我无法将列表中的所有项目放入单元格:

Traceback (most recent call last):
  File "ga.py", line 57, in <module>
    print_annotations(annotations)
  File "ga.py", line 49, in print_annotations
    sheet.cell(row=row, column=2, value=values)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/openpyxl/worksheet/worksheet.py", line 240, in cell
    cell.value = value
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/openpyxl/cell/cell.py", line 216, in value
    self._bind_value(value)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/openpyxl/cell/cell.py", line 199, in _bind_value
    raise ValueError("Cannot convert {0!r} to Excel".format(value))
ValueError: Cannot convert ['RID39466', 'RID39056', 'RID3874'] to Excel
python excel python-3.x openpyxl
1个回答
0
投票

这里的问题是list对象不是cell对象的有效值。要解决此问题,您必须传递一个有效值,例如stringfloat等。第二列中想要的结果是逗号分隔的列表。为了将字典中的值转换为正确格式的字符串,可以使用注释中提到的join方法。

'sep'.join(lst)

lst中的所有值,并将它们连接到以sep分隔的字符串中。因此

', '.join(values)

评估为代表逗号分隔列表的字符串。您可以将此字符串作为value对象的有效cell传递。

© www.soinside.com 2019 - 2024. All rights reserved.