Python Forum

Full Version: nested for loops to recursion
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Any advice on how to convert nested for loops to recursion. I'm kinda having trouble since I'm still a beginner.

The loops are for finding all the possible words in a Boggle game (Twisted Word search).
here's some sample recursive code, it's a method I use to display the contents of nested dictionaries
In this code, level is use to determine indentation level. line 32 calculates level * 4 spaces to determine how to indent
line 33 checks to see if value is a dictionary itself, and if so re curses using value as the dictionary
In this way, the dictionary tree can be walked.
food = {
    'Fruits and Fruit Juices': {
        'Acerola, (west indian cherry), raw': {
            'Nutrients': {
                'water': {
                    'unit': 'g',
                    'qty': '91.41'
                },
                'energy': {
                    'unit': 'kcal',
                    'qty': '32'
                }
            }
        },
    },
    'Figs, raw': {
        'Nutrients': {
            'water': {
                'unit': 'g',
                'qty': '91.41'
            },
            'energy': {
                'unit': 'kcal',
                'qty': '32'
            }
        }
    }
}

def display_dict(thedict, level=0):
    for key, value in thedict.items():
        sp = ' ' * (4 * level)
        if isinstance(value, dict):
            print(f'{sp}{key}:')
            level += 1
            display_dict(value, level)
        else:
            print(f'{sp}{key}: {value}')
            level -= 1

if __name__ == '__main__':
    display_dict(food)
results:
Output:
Fruits and Fruit Juices: Acerola, (west indian cherry), raw: Nutrients: water: unit: g qty: 91.41 energy: unit: kcal qty: 32 Figs, raw: Nutrients: water: unit: g qty: 91.41 energy: unit: kcal qty: 32