Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAndy McDonald
Python Development Techdegree Graduate 13,801 PointsKey error???
I have the following code:
import requests
url = "https://covid-api.mmediagroup.fr/v1/cases?country=All"
payload={}
headers = {}
response = requests.request("GET", url, headers=headers, data=payload)
data = response.json()
countries_list = []
countries = {}
for country in data:
base = data[country]['All']
new = {country : {'stats' : {'Confirmed' : base['confirmed'], 'Recovered' : base['recovered'], 'Deaths' : base['deaths']}}}
new[country]['stats']['Life expectancy'] = base['life_expectancy']
countries.update(new)
print(data)
Many keys will not work for some reason. One of them being life_expectancy and population and I dont understand why... Can someone pleeeaaaaseee help?
Here is an example of what the raw data looks like:
{'Afghanistan': {'All': {'confirmed': 154361, 'recovered': 0, 'deaths': 7183, 'country': 'Afghanistan', 'population': 35530081, 'sq_km_area': 652090, 'life_expectancy': '45.9', 'elevation_in_meters': None, 'continent': 'Asia', 'abbreviation': 'AF', 'location': 'Southern and Central Asia', 'iso': 4, 'capital_city': 'Kabul', 'lat': '33.93911', 'long': '67.709953', 'updated': '2021/09/17 04:21:46+00'}}
1 Answer
jb30
44,806 PointsThere are some places in the data that don't include keys for life expectancy or population, such as "Summer Olympics 2020". Instead of base['life_expectancy']
, have you tried something like base.get('life_expectancy', 'N/A')
? This will return the value for base[life_expectancy]
if it's a valid key, and will return 'N/A'
if base
does not have the key life_expectancy
.