Python Dictionary Hurricane Challenge Project

I am just about done with my Hurricane Analysis Project but am stuck on a few things. There are three problems within my code, all the same thing. Unreachable code at line 104, 143 and 171. The codes which are unreachable are max_mortality_cane(104), max_damage_cane(143) and hurricanes_by_damage(171).
I compared it to the solution and I just can not figure out what I am doing wrong!
any tips or nudges in the right direction would be much appreciated because I have been meticulously comparing mine to the solution for at least an hour now and have nothing…

Python Dictionaries Challenge Project | Codecademy

1. # names of hurricanes
2. names = ['Cuba I', 'San Felipe II Okeechobee', 'Bahamas', 'Cuba II', 'CubaBrownsville', 'Tampico', 'Labor Day', 'New England', 'Carol', 'Janet', 'Carla', 'Hattie', 'Beulah', 'Camille', 'Edith', 'Anita', 'David', 'Allen', 'Gilbert', 'Hugo', 'Andrew', 'Mitch', 'Isabel', 'Ivan', 'Emily', 'Katrina', 'Rita', 'Wilma', 'Dean', 'Felix', 'Matthew', 'Irma', 'Maria', 'Michael']

3. # months of hurricanes
4. months = ['October', 'September', 'September', 'November', 'August', 'September', 'September', 'September', 'September', 'September', 'September', 'October', 'September', 'August', 'September', 'September', 'August', 'August', 'September', 'September', 'August', 'October', 'September', 'September', 'July', 'August', 'September', 'October', 'August', 'September', 'October', 'September', 'September', 'October']

5. # years of hurricanes
6. years = [1924, 1928, 1932, 1932, 1933, 1933, 1935, 1938, 1953, 1955, 1961, 1961, 1967, 1969, 1971, 1977, 1979, 1980, 1988, 1989, 1992, 1998, 2003, 2004, 2005, 2005, 2005, 2005, 2007, 2007, 2016, 2017, 2017, 2018]

7. # maximum sustained winds (mph) of hurricanes
8. max_sustained_winds = [165, 160, 160, 175, 160, 160, 185, 160, 160, 175, 175, 160, 160, 175, 160, 175, 175, 190, 185, 160, 175, 180, 165, 165, 160, 175, 180, 185, 175, 175, 165, 180, 175, 160]

9. # areas affected by each hurricane
10. areas_affected = [['Central America', 'Mexico', 'Cuba', 'Florida', 'The Bahamas'], ['Lesser Antilles', 'The Bahamas', 'United States East Coast', 'Atlantic Canada'], ['The Bahamas', 'Northeastern United States'], ['Lesser Antilles', 'Jamaica', 'Cayman Islands', 'Cuba', 'The Bahamas', 'Bermuda'], ['The Bahamas', 'Cuba', 'Florida', 'Texas', 'Tamaulipas'], ['Jamaica', 'Yucatn Peninsula'], ['The Bahamas', 'Florida', 'Georgia', 'The Carolinas', 'Virginia'], ['Southeastern United States', 'Northeastern United States', 'Southwestern Quebec'], ['Bermuda', 'New England', 'Atlantic Canada'], ['Lesser Antilles', 'Central America'], ['Texas', 'Louisiana', 'Midwestern United States'], ['Central America'], ['The Caribbean', 'Mexico', 'Texas'], ['Cuba', 'United States Gulf Coast'], ['The Caribbean', 'Central America', 'Mexico', 'United States Gulf Coast'], ['Mexico'], ['The Caribbean', 'United States East coast'], ['The Caribbean', 'Yucatn Peninsula', 'Mexico', 'South Texas'], ['Jamaica', 'Venezuela', 'Central America', 'Hispaniola', 'Mexico'], ['The Caribbean', 'United States East Coast'], ['The Bahamas', 'Florida', 'United States Gulf Coast'], ['Central America', 'Yucatn Peninsula', 'South Florida'], ['Greater Antilles', 'Bahamas', 'Eastern United States', 'Ontario'], ['The Caribbean', 'Venezuela', 'United States Gulf Coast'], ['Windward Islands', 'Jamaica', 'Mexico', 'Texas'], ['Bahamas', 'United States Gulf Coast'], ['Cuba', 'United States Gulf Coast'], ['Greater Antilles', 'Central America', 'Florida'], ['The Caribbean', 'Central America'], ['Nicaragua', 'Honduras'], ['Antilles', 'Venezuela', 'Colombia', 'United States East Coast', 'Atlantic Canada'], ['Cape Verde', 'The Caribbean', 'British Virgin Islands', 'U.S. Virgin Islands', 'Cuba', 'Florida'], ['Lesser Antilles', 'Virgin Islands', 'Puerto Rico', 'Dominican Republic', 'Turks and Caicos Islands'], ['Central America', 'United States Gulf Coast (especially Florida Panhandle)']]

11. # damages (USD($)) of hurricanes
12. damages = ['Damages not recorded', '100M', 'Damages not recorded', '40M', '27.9M', '5M', 'Damages not recorded', '306M', '2M', '65.8M', '326M', '60.3M', '208M', '1.42B', '25.4M', 'Damages not recorded', '1.54B', '1.24B', '7.1B', '10B', '26.5B', '6.2B', '5.37B', '23.3B', '1.01B', '125B', '12B', '29.4B', '1.76B', '720M', '15.1B', '64.8B', '91.6B', '25.1B']

13. # deaths for each hurricane
14. deaths = [90,4000,16,3103,179,184,408,682,5,1023,43,319,688,259,37,11,2068,269,318,107,65,19325,51,124,17,1836,125,87,45,133,603,138,3057,74]

15. # write your update damages function here:

16. #def damages_float(damages):
17.  # conversion = {"M": 1000000, "B": 1000000000}
18.   #updated_damages = []
19.   
20.   #for amount in damages:
21.    # if amount[-1] == "M":
22.     #  updated_damages.append(float(amount.strip("M"))*conversion["M"])
23.    # if amount[-1] == "B":
24.    #   updated_damages.append(float(amount.strip("B"))*conversion["B"])
25.    # if amount == "Damages not recorded":
26.     #   print("Damages not recorded")
27.   #return updated_damages
28. def convert_damages_data(damages):
29.   """Convert damages data from string to float and return converted data as a list."""
30.   conversion = {"M": 1000000,
31.                "B": 1000000000}

32.   updated_damages = list()
33.   for damage in damages:
34.     if damage == "Damages not recorded":
35.       updated_damages.append(damage)
36.     if damage.find('M') != -1:
37.       updated_damages.append(float(damage[0:damage.find('M')])*conversion["M"])
38.     if damage.find('B') != -1:
39.       updated_damages.append(float(damage[0:damage.find('B')])*conversion["B"])
40.   return updated_damages


41. updated_damages = convert_damages_data(damages)

42. #print(updated_damages)

43. hurricanes = {}

44. # write your construct hurricane dictionary function here:
45. def create_dictionary(names, months, years, max_sustained_winds, areas_affected, updated_damages, deaths):
46.   num_hurricanes = len(names)
47.   for i in range(num_hurricanes):
48.     hurricanes[names[i]] = {"Name": names[i],
49.                           "Month": months[i],
50.                           "Year": years[i],
51.                           "Max Sustained Wind": max_sustained_winds[i],
52.                           "Areas Affected": areas_affected[i],
53.                           "Damage": updated_damages[i],
54.                           "Deaths": deaths[i]}
55.   return hurricanes


56. # create hurricanes dictionary
57. hurricanes = create_dictionary(names, months, years, max_sustained_winds, areas_affected, updated_damages, deaths)
58. #print(hurricanes)


59. # write your construct hurricane by year dictionary function here:
60. def hurricane_by_year(hurricanes):
61.   hurricane_year = {}
62.   for cane in hurricanes:
63.     current_year = hurricanes[cane]['Year']
64.     current_cane = hurricanes[cane]
65.     if current_year not in hurricane_year:
66.       hurricane_year[current_year] = [current_cane]
67.     else:
68.       hurricane_year[current_year].append(current_cane)
69.   return hurricane_year

70. hurricane_year = hurricane_by_year(hurricanes)
71. #print(hurricane_year[1932])

72. # write your count affected areas function here:
73. def affected_areas(hurricanes):
74.   hurricane_areas = {}
75.   for cane in hurricanes:
76.     for area in hurricanes[cane]["Areas Affected"]:
77.       if area not in hurricane_areas:
78.         hurricane_areas[area] = 1
79.       else:
80.         hurricane_areas[area] += 1
81.   return hurricane_areas
82. hurricane_areas = affected_areas(hurricanes)

83. #print(hurricane_areas)

84. # write your find most affected area function here:
85. def most_hit(hurricane_areas):
86.  max_area = "Central America"
87.  max_area_count = 0
88.  for area in hurricane_areas:
89.    if max_area_count < hurricane_areas[area]:
90.         max_area_count = hurricane_areas[area]
91.         max_area = area 
92.  return max_area, max_area_count


93. max_area, max_area_count = most_hit(hurricane_areas)

94. #print(max_area, max_area_count)


95. # write your greatest number of deaths function here:
96. def greatest_deaths(hurricanes):
97.   max_mortality_cane = 'Cuba I'
98.   max_mortality = 0
99.   for cane in hurricanes:
100.     if hurricanes[cane]['Deaths'] > max_mortality:
101.       max_mortality_cane = cane
102.       max_mortality = hurricanes[cane]['Deaths']
103.   return max_mortality_cane, max_mortality

104.   max_mortality_cane, max_mortality = greatest_deaths(hurricanes)

105.   print(max_mortality_cane, max_mortality)


106. # write your catgeorize by mortality function here:

107. def cat_by_mortality(hurricanes):
108.   mortality_scale = {0: 0,
109.                      1: 100,
110.                      2: 500,
111.                      3: 1000,
112.                      4: 10000}
113.   hurricanes_by_mortality ={0:[], 1:[], 2:[], 3:[], 4:[], 5:[]}
114.   for cane in hurricanes:
115.     num_deaths = hurricanes[cane]['Deaths']
116.     if num_deaths == mortality_scale[0]: 
117.       hurricanes_by_mortality[0].append(hurricanes[cane])
118.     elif num_deaths > mortality_scale[0] and num_deaths <= mortality_scale[1]:
119.       hurricanes_by_mortality[1].append(hurricanes[cane])
120.     elif num_deaths > mortality_scale[1] and num_deaths <= mortality_scale[2]:
121.       hurricanes_by_mortality[2].append(hurricanes[cane])
122.     elif num_deaths > mortality_scale[2] and num_deaths <= mortality_scale[3]:
123.       hurricanes_by_mortality[3].append(hurricanes[cane])
124.     elif num_deaths > mortality_scale[3] and num_deaths <= mortality_scale[4]:
125.       hurricanes_by_mortality[4].append(hurricanes[cane])
126.     elif num_deaths > mortality_scale[4]:
127.       hurricanes_by_mortality[5].append(hurricanes[cane])
128.   return hurricanes_by_mortality

129. hurricanes_by_mortality = cat_by_mortality(hurricanes)

130. #print(hurricanes_by_mortality)
131.   

132. # write your greatest damage function here:
133. def greatest_damage(hurricanes):
134.   max_damage_cane = 'Cuba I'
135.   max_damage = 0
136.   for cane in hurricanes:
137.     if hurricanes[cane]['Damage'] == "Damages not recorded":
138.       pass
139.     elif hurricanes[cane]['Damage'] > max_damage:
140.       max_damage_cane = cane
141.       max_damage = hurricanes[cane]['Damage']
142.   return  max_damage_cane, max_damage

143.   max_damage_cane, max_damage = greatest_damage(hurricanes)

144.   print(max_damage_cane, max_damage)   





145. # write your catgeorize by damage function here:
146. def cat_by_damage(hurricanes):
147.   damage_scale = {0: 0,
148.                   1: 100000000,
149.                   2: 1000000000,
150.                   3: 10000000000,
151.                   4: 50000000000}
152.   hurricanes_by_damage ={0:[], 1:[], 2:[], 3:[], 4:[], 5:[]}
153.   for cane in hurricanes:
154.     cane_damage = hurricanes[cane]['Damage']
155.     if cane_damage == "Damages not recorded":
156.       hurricanes_by_damage[0].append(hurricanes[cane])
157.     if cane_damage == damage_scale[0]:
158.       hurricanes_by_damage[0].append(hurricanes[cane])
159.     elif cane_damage > damage_scale[0] and cane_damage <= damage_scale[1]:
160.       hurricanes_by_damage[1].append(hurricanes[cane])   
161.     elif cane_damage > damage_scale[1] and cane_damage <= damage_scale[2]:
162.       hurricanes_by_damage[2].append(hurricanes[cane]) 
163.     elif cane_damage > damage_scale[2] and cane_damage <= damage_scale[3]:
164.       hurricanes_by_damage[3].append(hurricanes[cane]) 
165.     elif cane_damage > damage_scale[3] and cane_damage <= damage_scale[4]:
166.       hurricanes_by_damage[4].append(hurricanes[cane]) 
167.     elif cane_damage > damage_scale[4]:
168.       hurricanes_by_damage[5].append(hurricanes[cane])
169.   return hurricanes_by_damage

170.   hurricanes_by_damage = cat_by_damage(hurricanes)

171.   print(hurricanes_by_damage[3]) 

Hello! Lines 104, 143 and 171 are all indented to be within the function above. However, a return precedes them, which means the function is exited before the code reaches these lines.

ahh I figured it was something so simple like that but I just couldnt find it! Thank you!

1 Like

11 posts were split to a new topic: Why won’t this print?

In the OP’s code, line 36:
It looks like the line is written as “if the last indexed letter does NOT equal M, multiply the number by a million”. My question: Why is the code != versus ==?

You’d need to understand how the .find method operates which tends to be a quick look at the docs- str.find. Notably -1 does not indicate the last index of the the string but is the value returned then the substring cannot be found. Does != now make sense?

Assuming the exact index was unimportant if 'M' in damage: would perform the same task in a neat way.

1 Like

In line 66 I don’t understand why the OP used square brackets around current_cane on the right side of the equals sign. Ive played around with it and know that the code does not work without them. If you remove them it throws an error that points at the append function in line 68 with

AttributeError: 'dict' object has no attribute 'append'

Can someone help me understand this error a bit more? I redid the entire dictionaries lesson and I still do not understand why we get this error.

60. def hurricane_by_year(hurricanes):
61.   hurricane_year = {}
62.   for cane in hurricanes:
63.     current_year = hurricanes[cane]['Year']
64.     current_cane = hurricanes[cane]
65.     if current_year not in hurricane_year:
66.       hurricane_year[current_year] = [current_cane]
67.     else:
68.       hurricane_year[current_year].append(current_cane)
69.   return hurricane_year
1 Like

It’s because when you put the square brackets around current_cane, you are indicating that the dictionary value is in the form of a list, which allows you to use the ‘append’ method.

Some of the years had more than one hurricane, so you’d want to list each current_cane under the year key.
Without the square brackets, the dictionary value isn’t in list form, and you can’t append.
Using .update() will only include one hurricane for that year.

Hi!

I cannot add more than one key and values for the same key. I mean there is more than one hurricane for the same year. Here mentioned codes excludes the issue as far as I tried. Is there any solution?

Maybe the value should be a list or another dictionary. A list could contain a dictionary for each hurricane.

Oh thank you! Now I see. For one key, values in multiple lists should be appended. Thanks for quick reply. :slight_smile:

I think I misunderstood question 4, question 5 is asking me to do the exactly same thing? My answer to question 4:

def area_count(hurricane_dic):
    areas = {}
    for cane in hurricane_dic:
        for key in hurricane_dic[cane]['Areas Affected']:
            if key not in areas:
                areas[key] = 1
            else:
                areas[key] += 1
    return areas

aff_area = area_count(hurricane_dic)
print(aff_area)

question 5 is: Write a function that finds the area affected by the most hurricanes, and how often it was hit. Test your function on your affected area dictionary.

I already did that unless it just means access that index in the dictionary, which is so basic I don’t feel like that’s possible when considering the other questions (Which have taken me days… literal well its my 3rd day now I just started lol). My output is this btw:

{'Central America': 9, 'Mexico': 7, 'Cuba': 6, 'Florida': 6, 'The Bahamas': 7, 'Lesser Antilles': 4, 'United States East Coast': 3, 'Atlantic Canada': 3, 'Northeastern United States': 2, 'Jamaica': 4, 'Cayman Islands': 1, 'Bermuda': 2, 'Texas': 4, 'Tamaulipas': 1, 'Yucatn Peninsula': 3, 'Georgia': 1, 'The Carolinas': 1, 'Virginia': 1, 'Southeastern United States': 1, 'Southwestern Quebec': 1, 'New England': 1, 'Louisiana': 1, 'Midwestern United States': 1, 'The Caribbean': 8, 'United States Gulf Coast': 6, 'United States East coast': 1, 'South Texas': 1, 'Venezuela': 3, 'Hispaniola': 1, 'South Florida': 1, 'Greater Antilles': 2, 'Bahamas': 2, 'Eastern United States': 1, 'Ontario': 1, 'Windward Islands': 1, 'Nicaragua': 1, 'Honduras': 1, 'Antilles': 1, 'Colombia': 1, 'Cape Verde': 1, 'British Virgin Islands': 1, 'U.S. Virgin Islands': 1, 'Virgin Islands': 1, 'Puerto Rico': 1, 'Dominican Republic': 1, 'Turks and Caicos Islands': 1, 'United States Gulf Coast (especially Florida Panhandle)': 1}

Anyone know wat I have misunderstood? I am a perfectionist compulsively I wont be able to move on till i figure it out >.> …

The output you have posted shows the breakdown of how many hurricanes have affected each area.

Now, you need to write a function which finds the area affected by the most hurricanes. I don’t think the intent is for you to manually specify the index. Rather, the function should go through the dictionary and find the area affected by the most hurricanes.

For your sample output, the answer will be 'Central America' with 9 hurricanes. But the determination that 'Central America' is the most affected should not be done by you manually inspecting the output. Rather, the function should be able to compare all the key-value pairs and decide which entry should be returned.

Well what I mean is that by sorting the dictionary (I am only realizing now I didn’t post that part of the code I did it in the question beforehand), it does show the most affected place. Then it can just be accessed by choosing the first index no matter which one it is because the “area” or key/variable wtv with the most “Hurricanes”/value had already been indexed properly to be first no matter what. So its not just a mechanical version of me choosing, it was done through the code. That is okay? (In the sense that it is what the question is asking me to do) (Thz for reply btw!)

Can you share your code for sorting the dictionary? That could help in forming a opinion as to whether your approach accomplishes the specified task successfully.

yeah no problem ill send it later today when I’m doing my new project, or i think it should be on my github also if youd prefer just to check that out Carpen-Them-Diemz/1.1-Codecademy: Codecademy projects and etc (github.com)

no idea why that url came out like that but okay ill assume it works lol its in the 1.1 repository in all projects, coded correspondence I believe (If you feel like looking at anything else to give some feedback wouldn’t mind that! Especially the hurricane one, the rest I don’t really consider ‘projects’ and don’t rly need feedback, not that i wouldn’t appreciate it!).

Thanks for sharing your code. No need to send it again. The github link works.

I looked at the area_max function and it seems to give the correct output for the dictionary being used in the project. I agree with your assertion that you are accomplishing the task through code (and not by manually doing a visual inspection). But, I am having a bit of difficulty in following the logic, so I can’t comment upon the correctness of the code.

Don’t remember which part did the sorting at this point but I do know one of the questions my answer was absolutely ridiculous :sweat_smile: probably that one i imagine? xD You’d know if it was lol. I was struggling a lot at that point before it all clicked and since i wasn’t looking up answers or anything it ended up a bit frankensteined, after spending so much time on the project (like 3 days which is absolutely insane for me), I just wasn’t willing to go back and fix it. I forgot about that honestly, will probably go fix it while doing my next one. Just to give u an example of y 3 days is so ridiculous, the project after that took me literaly, and I mean literally literally, 7 minutes… >.>

I’m glad it’s accomplishing what it was supposed to at least though. So thank you very much for verifying that. When I originally posted it, it was on the same day I finished the project and I swear I had nervous ticks going on from being so stressed. Don’t think it has ever taken me 3 days to understand anything I was learning before, I gotta say its honestly kind of nice though. I’ve never really struggled with anything before and I have ADD so once it’s finished and out of my sight, I’m usually done thinking about it for a while. Without having to spend much time solving the problem/doing the work, the process gets a lot less defined in your brain, I swear I learnt more struggling on that project for those 3 days than the whole other 2 weeks and 50% of the path I’ve done. At first I was a bit annoyed by the seemingly esoteric leap in project difficulty for me and ppl in that situation, but after seeing the difference in how much i progressed I wish they’d do it more.

1 Like