I am looking at building lists of lists within a dictionary from an Excel spreadsheet.
My spreadsheet looks like this:
| 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 |
My output dictionary should looks like this:
{ "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" }] }] }
With the following code I only get the last values in each of the lists:
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)
--> result
{ "source_id1": ["target_id2", [{ "find_string": "ijkl2", "replace_sting": "mnop2" } ]], "source_id2": ["target_id4", [{ "find_string": "opqr", "replace_sting": "stuv" } ]] }
source_idxpoints to a list of dictionaries, each with one key only (target_idx)? It might feel more natural to have that be a dictionary instead of a list, with a key-value relationship.find_replace_listandfind_replace_dict.xlrd.open_workbookseems to fail in Python 3.9.