How to iterate through a nested dict?

前端 未结 7 1011
谎友^
谎友^ 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.

    0 讨论(0)
  • 2020-12-09 00:09

    To get keys and values you need dict.items():

    for key, value in d.items():
        print(key)
    

    If you want just the keys:

    for key in d:
        print(key)
    
    0 讨论(0)
  • 2020-12-09 00:10

    if given dictionary pattern has monotone format and keys are known

    dict_ = {'0': {'foo': 1, 'bar': 2}, '1': {'foo': 3, 'bar': 4}}
    for key, val in dict_.items():
        if isinstance(val, dict):
            print(val.get('foo'))
            print(val.get('bar'))
    

    in this case we can skip nested loop

    0 讨论(0)
  • 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 :)

    0 讨论(0)
  • 2020-12-09 00:12

    you can iterate all keys and values of nested dictionary as following:

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

    Your output looks like this -

    foo -> 1
    bar -> 2
    baz -> 3
    quux -> 4
    
    0 讨论(0)
  • 2020-12-09 00:14

    Iterating through a dictionary only gives you the keys.

    You told python to expect a bunch of tuples, and it tried to unpack something that wasn't a tuple (your code is set up to expect each iterated item to be of the form (key,value), which was not the case (you were simply getting key on each iteration).

    You also tried to print Key, which is not the same as key, which would have led to a NameError.

    for key in d:
        print(key)
    

    should work.

    0 讨论(0)
提交回复
热议问题