How to iterate through a nested dict?

前端 未结 7 1032
谎友^
谎友^ 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:04

    keys() method returns a view object that displays a list of all the keys in the dictionary

    Iterate nested dictionary:

    d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}
    
    for i in d.keys():
        print i
        for j in d[i].keys():
            print j
    

    OR

    for i in d:
        print i
        for j in d[i]:
            print j
    

    output:

    dict1 
    foo
    bar
    
    dict2
    baz 
    quux
    

    where i iterate main dictionary key and j iterate the nested dictionary key.

提交回复
热议问题