Hurricane Analysis step 3

Hello everyone! I’m working on the Hurricane Analysis project. In the step 3, we have to create a dictionary with all the data about every hurricane.
First, I have tried this code:

def hurricane_data(names, months, years, max_sustained_winds, areas_affected, damages, deaths):
    for i in range(0, len(names)):
         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": damages[i]}}
    return hurricanes

But it only printed the data about the last hurricane on the list. However, this code printed the data of all the hurricanes:

`def hurricane_data(names, months, years, max_sustained_winds, areas_affected, damages, deaths):
    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": damages[i]} for i in range(0, len(names))}
    return hurricanes`

Why the second one works and the e doesn’t??? :thinking:

Consider how assignment works in Python. If you reassign a name then your name simply references the most recent assignment, the old one does not mater.

By example:

lst = [1, 2, 3]
for idx in range(len(lst)):
    number = lst[idx]

print(number)

The dictionary comprehension is a different set-up entirely. Like list comprehensions it builds up the dictionary. This behaves much like it would if you instead mutated the same dictionary by adding extra key-value pairs to it.

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.