在 python 的嵌套字典中应用循环时出错

Getting error while applying loop in a nested Dictionary in python

我有一个嵌套字典,里面有一些键值对 并在应用 FOR LOOP 从中获取值时出错。代码就像:

gl = { 'GLEN' : {'GLENS08907' : {'801-011-02M' : 'GLEN PART'}}
       ,'GLENS10062': {'M85049/38': 'RTIO PART'}
}

for mfr,doc in gl.items():
    print('Print Mfr is : ',mfr)
    for i, k in doc.items():
        print('Doc is : ', i)
        for key in k:
            print(key + ' : '  , k[key] )

我试图获得如下输出:

Print Mfr is :  GLEN
Doc is :  GLENS08907
801-011-02M :  GLEN PART
Doc is :  GLENS10062
M85049/38 :  RTIO PART

但是执行代码后报错

Print Mfr is :  GLEN
Doc is :  GLENS08907
801-011-02M :  GLEN PART
Print Mfr is :  GLENS10062
Doc is :  M85049/38
Traceback (most recent call last):
   line 90, in <module>
    print(key + ' : '  , k[key] )
TypeError: string indices must be integers

请建议在嵌套字典中使用 For 循环的正确方法。

在你的字典里gl['GLEN'] = 'GLEN' : {'GLENS08907' : {'801-011-02M' : 'GLEN PART'} 在 nested dictionary 中有 nested dictionary 但 gl['GLENS10062'] = {'M85049/38': 'RTIO PART'} doesn't have nested dictionary 。 所以在代码中 print(key + ' : ' , k[key] ) 键是 R 而不是 RTIO PART.