Home > other >  Looping through nested dictionary - Python
Looping through nested dictionary - Python

Time:04-29

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:

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?

CodePudding user response:

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/

  • Related