Skip to content
Advertisement

Iterating over nested dictionary returns only first element

I have this nested dictionary (“dictionary of dictionaries”)

JavaScript

And I want to create a new one which would consist of outer keys associated with inner values (see expected output below) I use this recursive function:

JavaScript

But when I try to print that:

JavaScript

I get this (only the first dictionary is processed:

JavaScript

But I would like to have something like this (all dictionaries processed)

JavaScript

What am I doing wrong?

Thank you very much in advance for any help.

Advertisement

Answer

The problem is that when you call return myPrint(v, k) for the first time you compute the values for the first dictionary and then return instead of continuing to the other values in the for loop.

Changing the function to:

JavaScript

will return a big dictionary, for you example:

JavaScript

However, the function can be nicely packed in a non-recursive way as follow:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement