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])
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With