Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append to list while in recursive loop

I'm trying to create a recursive function that takes a JSON dictionary and stores any value with key names 'rate' into a list. I will then take that list and find the lowest value. My code looks like this right now, but is producing multiple empty lists within the list.

def recurse_keys(df):
    rates = []
    for key, value in df.items():
        if key == 'rate':
            rates.append(value)
        if isinstance(df[key], dict):
            recurse_keys(df[key])
like image 408
Casey Avatar asked Dec 01 '22 16:12

Casey


2 Answers

You need to combine the results from the recursion, and return it:

def recurse_keys(df):
    rates = []
    for key, value in df.items():
        if key == 'rate':
            rates.append(value)
        if isinstance(df[key], dict):
            rates += recurse_keys(df[key])
    return rates
like image 172
Fabricator Avatar answered Dec 05 '22 09:12

Fabricator


  1. extend your result list with the result from the recursive call
  2. don't forget to return your result

Code:

def recurse_keys(df):
    rates = []
    for key, value in df.items():
        if key == 'rate':
            rates.append(value)
        if isinstance(df[key], dict):
            rates += recurse_keys(df[key])
    return rates
like image 34
timgeb Avatar answered Dec 05 '22 09:12

timgeb