Home > Software engineering >  How to print multilevel nested dictonary in python
How to print multilevel nested dictonary in python

Time:12-03

Here is my code

     print(data['a'][0]['aa'])
    print(data['a'][0].keys())

This is input->

    data={
        'a':[{
            'aa':{'aax':5,'aay':6,'aaz':7},
            'ab':{'abx':8,'aby':9,'abz':10}
            },
            {
            'aaa':{'aaax':11,'aaay':12,'aaaz':13},
            'aab':{'aabx':14,'aaby':15,'aabz':16}
            }]
    }
    
    
   

How can i print the dictionary like this output

    Output:
    
    Key:aax Value: 5
    Key:aay Value: 6
    Key:aaz Value: 7
    Key:abx Value: 8
    Key:aby Value: 9
    Key:abz Value: 10
    Key:aaax Value: 11

How can i loop through in this type of data.How can i loop through and print all the data I can access the single data but how can print all data.

CodePudding user response:

just use simple for loop

for outer_list in data['a']:
    for outer_key, outer_value in outer_list.items():
        for key, value in outer_value.items():
            print("Key: {}, Value: {}".format(key, value))

output:

Key: aax, Value: 5
Key: aay, Value: 6
Key: aaz, Value: 7
Key: abx, Value: 8
Key: aby, Value: 9
Key: abz, Value: 10
Key: aaax, Value: 11
Key: aaay, Value: 12
Key: aaaz, Value: 13
Key: aabx, Value: 14
Key: aaby, Value: 15
Key: aabz, Value: 16

CodePudding user response:

To print all the key-value pairs in a multilevel nested dictionary, you can use a nested loop structure. Here is an example:

for outer_dict in data['a']:
    for inner_dict in outer_dict.values():
        for key, value in inner_dict.items():
            print(f"Key: {key} Value: {value}")
  • Related