Python Dictionary Challenge Hurricane Analysis

I am currently working on the Hurricane Analysis project and am on part 3
link: Python Dictionaries Challenge Project | Codecademy

I am going crazy over this! The function should have made the hurricane name into the key,
but when I try to print using the key name, it gives me a KeyError saying it is not in the dictionary.
I have already tried viewing this part of the solution and still can not figure it out. As far as I can tell, my code is nearly identical to the solution besides the name of the function and the indent on return. Not sure if it has anything to do with the indent but when I make it the same indentation as the solution, I receive this error:
Traceback (most recent call last):
File “script.py”, line 55, in
hurricanes = hurricane_dict(names, months, years, max_sustained_winds, areas_affected, updated_damages, deaths)
File “script.py”, line 51, in hurricane_dict
“Damage”: updated_damages[i],
IndexError: list index out of range

So I am at a total loss of what the issue may be.

# write your construct hurricane dictionary function here:
def hurricane_dict(names, months, years, max_sustained_winds, areas_affected, updated_damages, deaths):
  hurricanes = {}
  num_hurricanes = len(names)
  for i in range(num_hurricanes):
    hurricanes[names[i]] = {"Name": names[i], "Month": months[i], "Year": years[i], "Max Sustained Wind": max_sustained_winds[i], "Areas Affected": areas_affected[i], "Damage": updated_damages[i], "Deaths": deaths[i]}
    return hurricanes

hurricanes = hurricane_dict(names, months, years, max_sustained_winds, areas_affected, updated_damages, deaths)
print(hurricanes["Edith"])

Thank you!

Hi,

For sure the indentation here is going to cause trouble (since the loop runs once and ends the entire function with the return statement):

  for i in range(num_hurricanes):
    hurricanes[names[i]] = {"Name": names[i], "Month": months[i], "Year": years[i], "Max Sustained Wind": max_sustained_winds[i], "Areas Affected": areas_affected[i], "Damage": updated_damages[i], "Deaths": deaths[i]}
    return hurricanes

so I think you want to indent that return so it doesn’t do that.
As it is currently you would only have the first entry in your hurricanes dict. Try placing a few strategic print statements to highlight what your code is doing… you may find the answer you’re looking for.

Hope this helps.

1 Like