Search code examples
pythonnested-for-loop

Getting error while applying loop in a nested Dictionary in python


I have a Nested dictionary which has some key values pair in it and getting error while applying FOR LOOP to get the values from it. Code is like :

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] )

I was trying to get the output like :

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

But getting error after the excution of code.

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

Please suggest the right way to use For loop in nested dictionary.


Solution

  • In your dictionary gl['GLEN'] = 'GLEN' : {'GLENS08907' : {'801-011-02M' : 'GLEN PART'} is have nested dictionary within nested dictionary but gl['GLENS10062'] = {'M85049/38': 'RTIO PART'} doesn't have nested dictionary . So in code print(key + ' : ' , k[key] ) key is R instead of RTIO PART.