Most_Recent_Net_Income = float(json_r['financials'][0]['Net Income'])
Net_income_1_year = float(json_r['financials'][1]['Net Income'])
Net_income_2_year = float(json_r['financials'][2]['Net Income'])
Net_income_3_year = json_r['financials'][3]['Net Income']
Net_income_4_year = json_r['financials'][4]['Net Income']
I feel like this bit of code is very repetitive, and was wondering how I could simplify it?
Thank you in advance
Something like this might help:
incomes = [i['Net Income'] for i in json_r['financials'][:5]]
Most_Recent_Net_Income, Net_income_1_year, Net_income_2_year,
Net_income_3_year, Net_income_4_year = map( float, incomes)
if in you version of python map()
returns <map object>
or something, you might want to wrap that in list()
to make it work better.
Just use a single dictionary instead of multiple variables:
income_by_year = {}
for year in range(0, 5):
income_by_year[year] = json_r['financials'][year]['Net Income']
print('Income in year 4:', income_by_year[4])
Or a dict comprehension:
income_by_year = {year: json_r['financials'][year]['Net Income']
for year in range(0, 4)}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.