How to iterate through a nested dict?

前端 未结 7 1026
谎友^
谎友^ 2020-12-08 23:50

I have a nested python dictionary data structure. I want to read its keys and values without using collection module. The data structu

7条回答
  •  轮回少年
    2020-12-09 00:12

    As the requested output, the code goes like this

        d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}
    
        for k1,v1 in d.iteritems(): # the basic way
            temp = ""   
            temp+=k1
            for k2,v2 in v1.iteritems():
               temp = temp+" "+str(k2)+" "+str(v2)
            print temp
    

    In place of iteritems() you can use items() as well, but iteritems() is much more efficient and returns an iterator.

    Hope this helps :)

提交回复
热议问题