Skip to content
Advertisement

Recursing python dictionaries with yield from to generate list of nested dictionary keys

I want to generate a list of unique nested keys for each value in a dictionary such that:

JavaScript

I thought something along these lines would work, appending each key to a list and recursing until a value is reached. At which point I yield a list and carry on.

JavaScript

However when running, the result is all the unique keys

JavaScript

Think I must be missing something here on how yielding / input arguments work

Advertisement

Answer

You keep modying the same list object (the reassignment of a local variable at the end there has no effect for any recursive call up or down the stack)! A simpler approach without a carry-over variable would be:

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