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

Deepakvg
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
Bjorn

The answer of script0 results in an output that starts with a forward slash (/). I modified script0's code a little:

def flatten(x, parent=''):
    for key in x.keys():
        if isinstance(x[key], dict) and parent == '': flatten(x[key], key)
        elif isinstance(x[key], dict) and parent != '': flatten(x[key], f"{parent}/{key}")
        elif not isinstance(x[key], dict) and parent == '': print(f"{key}: {x[key]}")
        else: print(f"{parent}/{key}: {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)

Output (without the leading /):

items/heading: Maps
items/description: Maps123
items/imagepath: /music/images/
items/config/config1: 12
items/config/config2: 123
db/username: xyz
db/password: xyz
version: v1

Please note that you could also create a new dictionary with the left-hand side of the output as the keys and the right-hand side as the values.

For example:

new_dict = {}

def flatten(x, parent=''):
    for key in x.keys():
        if isinstance(x[key], dict) and parent == '': flatten(x[key], key)
        elif isinstance(x[key], dict) and parent != '': flatten(x[key], f"{parent}/{key}")
        elif not isinstance(x[key], dict) and parent == '': new_dict[key] = x[key]
        else: new_dict[f"{parent}/{key}"] = 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)
print(new_dict)

Output:

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Loop through all nested dictionary values?

Loop through all nested dictionary values?

How to loop through all controls and get its id and values in Android?

How to cast dictionary key and value all at once in Swift4?

Add all of the key values in a nested Dictionary

nested for loop doesn't give all outputs

Python : Check specific key in nested dictionary and return all previous keys if its matched

How to loop all class variables with key and value

Iterate through dictionary with foreach loop and fetch all key/value pairs with value subset items

How to get all values with the same key in a nested dictionary in Python?

How to collapse all the nested Accordions if clicked on its parent Accordion?

Loop through all documents in a nested function

Loop through dictionary + multiplying all the values

How do I loop through all values in a dictionary if the values are dates

How delete all keys in a nested dictionary if the key equals a given key

Is there a way to access a nested dictionary with a concatenated string key?

going through all values in nested dictionary in Python

How to put both a key and its value from a dictionary through a function

Loop looping through last value in dictionary key instead of all values in dictionary

How can i apply loop on snapshot and append all data in ul li with its key and value?

How to remove key and all its values in a nested dictionary then change and arrange keys in this "0","1","2","3" order like it was before in Python

How to access all key value of dictionary with specific format

How to replace a key:value pair by its value whereever the chosen key occurs in a many-times-nested dictionary?

How to loop through a directory and all of its sub-directories?

How to loop through all same name parent and child nodes

Loop Through Two Dataframe Columns to Create Key-Value Pairs For Value Dictionaries Nested Inside A Dictionary Nested Inside Another Dictonary

loop through nested dictionary in python and display key value pair

How to extract into lists all the values for each key in a nested dictionary

loop through nested dictionary/list in Python and save key-value pairs