Python:遍历嵌套字典时出现冗余

Python: Redundancy when iterating through nested dictionary

我有一个嵌套字典,我正试图遍历它以写入 excel 文件。

这是启动和创建嵌套字典的代码

def tree(): return defaultdict(tree)
KMstruct = tree()
for system in sheet.columns[0]:
if system.value not in KMstruct:
    KMstruct[system.value]
    for row in range(1,sheet.get_highest_row()+1):
        if sheet['A'+str(row)].value == system.value and sheet['B'+str(row)].value not in KMstruct:
            KMstruct[system.value][sheet['B'+str(row)].value]
            if sheet['B'+str(row)].value == sheet['B'+str(row)].value and sheet['C'+str(row)].value not in KMstruct:
                KMstruct[system.value][sheet['B'+str(row)].value][sheet['C'+str(row)].value]
                if sheet['C'+str(row)].value == sheet['C'+str(row)].value and sheet['D'+str(row)].value not in KMstruct:
                    KMstruct[system.value][sheet['B'+str(row)].value][sheet['C'+str(row)].value][sheet['D'+str(row)].value]
                    KMstruct[system.value][sheet['B'+str(row)].value][sheet['C'+str(row)].value][sheet['D'+str(row)].value] = [sheet['E'+str(row)].value]

这是我循环的代码:

for key in KMstruct.keys():
r += 1
worksheet.write(r, col,     key)
for subkey in KMstruct[key]:
    if currsubkeyval != subkey:
        r += 1
        worksheet.write(r, col,     key)
    r +=1
    worksheet.write(r, col, key + '\' + subkey)
    for item in KMstruct[key][subkey]:
        if curritemval != item:
            r +=1
            worksheet.write(r, col, key + '\' + subkey)
        for subitem in KMstruct[key][subkey][item]:
            r += 1
            worksheet.write(r, col, key + '\' + subkey + '\' + item)
            worksheet.write(r, col + 1, subitem)
            curritemval = item
            for finalitem in KMstruct[key][subkey][item][subitem]:
                r += 1
                worksheet.write(r, col, key + '\' + subkey + '\' + item + '\' + subitem)
                worksheet.write(r, col + 1, KMstruct[key][subkey][item][subitem])

因为我是菜鸟,请耐心等待这段代码,我知道这不是那么漂亮。无论如何,我的问题是最后一个循环。我正在尝试获取 KMstruct[key][subkey][item][subitem] 中的字符串值,但是循环变量 lastitem 遍历键的字符串值的每个字符(注意:键 subitem 包含一个字符串列表)。这意味着如果我只有一个值要写入,它会被写入与字符串中的字符一样多的次数。

例如:值:apple 将被写在一个新的excel行上5次

我在这里做错了什么?

编辑:冗余问题已经解决,但现在我需要了解在将我的 lastitem(即我的字符串列表)分配给子项键时是否做错了什么。

您的直接问题是示例的最后一行应该是:

                worksheet.write(r,col+1, finalitem)

顺便说一句,如果您偶尔创建临时变量,您的代码会更容易阅读:

        subitemlist = KMstruct[key][subkey][item]
        for subitem in subitemlist:

问题是在Python中一个str也是一个可迭代对象,例如:

>>> for s in 'hello':
...    print(s)

h
e
l
l
o

所以你要么需要避免在值为 str 时进行迭代,要么将 str 包装在另一个可迭代对象(例如 list)中,以便可以处理它同样的方式。这会因您构建代码的方式而变得有些困难。例如,以下内容:

for key in KMstruct.keys():
    for subkey in KMstruct[key]:

...可以写成:

for key, value in KMstruct.items():
    for subkey, subvalue in value.items():

...在每个循环中为您提供,使应用测试成为可能。

for key, val in KMstruct.items():
r += 1
worksheet.write(r, col,     key)

for subkey, subval in val.items():
    if currsubkeyval != subkey:
        r += 1
        worksheet.write(r, col,     key)
    r +=1
    worksheet.write(r, col, key + '\' + subkey)

    for item, itemval in subval.items():
        if curritemval != item:
            r +=1
            worksheet.write(r, col, key + '\' + subkey)

        for subitem, subitemval in itemval.items():
            r += 1
            worksheet.write(r, col, key + '\' + subkey + '\' + item)
            worksheet.write(r, col + 1, subitem)
            curritemval = item

            # I am assuming at this point subitemval is either a list or a str?
            if type(subitemval) == str:
                # If it is, wrap it as a list, so the next block works as expected
                subitemval = [subitemval] 

            for finalitem in subitemval:
                r += 1
                worksheet.write(r, col, key + '\' + subkey + '\' + item + '\' + subitem)
                worksheet.write(r, col + 1, finalitem) # This should be finalitem, correct?

这里我们测试 subitemval 的类型,如果它是 str 则将其包装在列表 [str] 中,以便下面的块按预期进行迭代。还有一个明显的错误,您没有在最后一行输出 finalitem 。如果没有您的示例数据,则无法对其进行测试,但它在功能上应该是等效的。