Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to loop through all nested dictionary to give all the parent key concatenated and its value

dictionary={' items': { 'heading': 'Maps','description':'Maps123','imagepath':/music/images/','config':{'config1':12,'config2':123}},'db':{'username':'xyz','password':'xyz'},'version':'v1'}

I want the output in the format:

items/heading: Maps

items/description: Maps123

items/image_path: /music/images/v2/web_api-music.png

items/config/config1: abcd

items/config/config2: hello

db/username: xyz

db/password: xyz

version: v1

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Check it :

def flatten(x, parent=''):
    for key in list(x.keys()):
        if( type(x[key]) is dict ):
            flatten(x[key], parent+'/'+str(key))
        else:
            print(parent+'/'+str(key)+': ' + str(x[key]))

dictionary={'items': { 'heading': 'Maps','description':'Maps123','imagepath':'/music/images/','config':{'config1':12,'config2':123}},'db':{'username':'xyz','password':'xyz'},'version':'v1'}

flatten(dictionary)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading