【发布时间】:2021-11-25 23:50:40
【问题描述】:
我正在研究从 Excel 电子表格的字典中构建列表列表。
我的电子表格如下所示:
| source_item_id | target_item_id | find_sting | replace_sting |
|---|---|---|---|
| source_id1 | target_id1 | abcd1 | efgh1 |
| source_id1 | target_id1 | ijkl1 | mnop1 |
| source_id1 | target_id2 | abcd2 | efgh2 |
| source_id1 | target_id2 | ijkl2 | mnop2 |
| source_id2 | target_id3 | qrst | uvwx |
| source_id2 | target_id3 | yzab | cdef |
| source_id2 | target_id4 | ghij | klmn |
| source_id2 | target_id4 | opqr | stuv |
我的输出字典应该是这样的:
{ "source_id1": [{ "target_id1": [{ "find_string": "abcd1", "replace_string": "efgh1" }, { "find_string": "ijkl1", "replace_string": "mnop1" }] }, { "target_id2": [{ "find_string": "abcd2", "replace_string": "efgh2" }, { "find_string": "ijkl2", "replace_string": "mnop2" }] }], "source_id2": [{ "target_id3": [{ "find_string": "qrst", "replace_string": "uvwx" }, { "find_string": "yzab", "replace_string": "cdef" }] }, { "target_id4": [{ "find_string": "ghij", "replace_string": "klmn" }, { "find_string": "opqr", "replace_string": "stuv" }] }] }
使用以下代码,我只能获得每个列表中的最后一个值:
import xlrd xls_path = r"C:\data\ItemContent.xlsx" book = xlrd.open_workbook(xls_path) sheet_find_replace = book.sheet_by_index(1) find_replace_dict = dict() for line in range(1, sheet_find_replace.nrows): source_item_id = sheet_find_replace.cell(line, 0).value target_item_id = sheet_find_replace.cell(line, 1).value find_string = sheet_find_replace.cell(line, 2).value replace_sting = sheet_find_replace.cell(line, 3).value find_replace_list = [{"find_string": find_string, "replace_sting": replace_sting}] find_replace_dict[source_item_id] = [target_item_id] find_replace_dict[source_item_id].append(find_replace_list) print(find_replace_dict)
--> 结果
{ "source_id1": ["target_id2", [{ "find_string": "ijkl2", "replace_sting": "mnop2" } ]], "source_id2": ["target_id4", [{ "find_string": "opqr", "replace_sting": "stuv" } ]] }
【问题讨论】:
-
出于好奇 - 这有点正交 -
source_idx指向一个字典列表,每个只有一个键 (target_idx) 是否有原因?使用键值关系将其作为字典而不是列表可能会更自然。 -
错误最有可能在for循环的最后三行;我很确定您在这里覆盖了字典值。我建议通过调试器运行它并在每一步检查输出。最坏情况:使用打印语句打印
find_replace_list和find_replace_dict的值。 -
您使用的是旧版本的 Python 吗?
xlrd.open_workbook在 Python 3.9 中似乎失败了。
标签: python json list dictionary nested