import csv, json, statistics from html import escape rows = list(csv.DictReader(open('gapminderDataFiveYear.csv', encoding='utf-8-sig'))) rows2007 = [r for r in rows if str(r.get('year')) == '2007'] for row in rows2007: row['gdp_per_capita'] = round(float(row['gdpTotal']) / float(row['pop']), 6) with open('gapminder_2007.json', 'w', encoding='utf-8') as f: json.dump(rows2007, f, ensure_ascii=False, indent=2) gdp = [float(r['gdp_per_capita']) for r in rows2007] life = [float(r.get('lifeExp') or r.get('life') or 0) for r in rows2007] # Aggregate 2007 metrics by continent: mean life expectancy and mean GDP per # capita for each continent, sorted by life expectancy. by_continent = {} for r in rows2007: continent = r.get('continent') or 'Unknown' entry = by_continent.setdefault(continent, {'life': [], 'gdp': [], 'pop': []}) entry['life'].append(float(r.get('lifeExp') or r.get('life') or 0)) entry['gdp'].append(float(r['gdp_per_capita'])) entry['pop'].append(float(r.get('pop') or 0)) continent_stats = [] for continent, vals in by_continent.items(): continent_stats.append({ 'continent': continent, 'countries': len(vals['life']), 'mean_lifeExp': round(statistics.mean(vals['life']), 2) if vals['life'] else 0, 'mean_gdpPercap': round(statistics.mean(vals['gdp']), 2) if vals['gdp'] else 0, 'mean_population': round(statistics.mean(vals['pop']), 2) if vals['pop'] else 0, }) continent_stats.sort(key=lambda c: c['mean_lifeExp'], reverse=True) by_country = {} for row in rows: by_country.setdefault(row['country'], {})[row['year']] = float(row['pop']) growth = {country: years['2007'] - years['1952'] for country, years in by_country.items() if '1952' in years and '2007' in years} fastest_growth_country = max(growth, key=growth.get) with open('continent_2007_stats.csv', 'w', newline='', encoding='utf-8') as f: writer = csv.DictWriter(f, fieldnames=['continent', 'countries', 'mean_lifeExp', 'mean_gdpPercap', 'mean_population']) writer.writeheader() writer.writerows(continent_stats) palette = {'Asia': '#2563eb', 'Americas': '#db2777', 'Europe': '#15803d'} min_gdp, max_gdp = min(gdp), max(gdp) min_life, max_life = min(life), max(life) points = [] axis_labels = ( '' f'{min_gdp:.0f}' f'{max_gdp:.0f}' 'GDP per capita' f'{min_life:.1f}' f'{max_life:.1f}' 'Life expectancy (years)' ) legend = '
' + ' · '.join( f'● {escape(continent)}' for continent, color in palette.items()) + '
' for row in rows2007: country = escape(row['country']) continent = escape(row['continent']) per_capita = float(row['gdp_per_capita']) life_exp = float(row['lifeExp']) x = 65 + (per_capita - min_gdp) / max(max_gdp - min_gdp, 1) * 500 y = 280 - (life_exp - min_life) / max(max_life - min_life, 1) * 220 points.append( f'' f'{country}: GDP/person {per_capita:.1f}, life {life_exp:.1f}' ) rows_html = [] bars = [] max_population = max(item['mean_population'] for item in continent_stats) for index, item in enumerate(continent_stats): continent = escape(item['continent']) mean_population = item['mean_population'] rows_html.append( f'' f'{continent}{item["countries"]}{mean_population:,.2f}' ) y = 15 + index * 42 bars.append( f'{continent}' f'' ) report = ( 'Gapminder 2007 report' '
' '

2007 GDP per capita and life expectancy

' f'

' f'Fastest absolute population growth (1952–2007): {escape(fastest_growth_country)}, ' f'+{growth[fastest_growth_country]:,.0f} people.

' '

GDP per capita vs life expectancy by continent

' '' + axis_labels + ''.join(points) + '' + legend + '

Mean population by continent, 2007

' '' + ''.join(rows_html) + '
ContinentCountriesMean population
' f'' + ''.join(bars) + '
' ) with open('report.html', 'w', encoding='utf-8') as handle: handle.write(report)