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

Looping through nested dictionary – Python

I have written a function which takes 2 arguments:

myfunction(arg1, arg2)

Now, I would like to pass through this function keys and values from a dictionary:

    pairs = {
        "pair1": {"key1": "value1"},
        "pair2": {"key2": "value2"},    
        "pair3": {"key3": "value3"},
}

so that I would run my function on every combination of key & value.I tried to achieve it with this loop:

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

for key, value in pairs.items():
    results = myfunction(key, value)

which must be an incorrect way given the empty output. How should I propely call key and value into the loop?

>Solution :

you can try this. Printing is just for you to understand what’s going on.
In addition, a simple google search would’ve showed you some solid information.

for item in pairs.values():
   for key, value in item.items():
       print(key + " " + value)

Good luck.

see this: (Credit- GeeksforGeeks) https://www.geeksforgeeks.org/python-how-to-iterate-over-nested-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