Why do I have to define the dictionary twice?

Can anyone help me understand why my code (see screen shot below) returns the error?

Didn’t I already define the updated_hurricane_table in the function? If I put the print line print(updated_hurricane_table) inside the function, it prints the combined dictionary that I want, so I’m confident my code mostly makes sense. It’s only when I remove the print line from the function and simply ask the function to return updated_hurricane_table that the problem arises. I call the function (presumably creating the updated_hurricane_table dictionary and returning it) and then ask to print only the first key from the dictionary (“Cuba I”) and I get told updated_hurricane_table is not defined. What’s up?

When I look at the provided solution, it confirms that I’m creating the dictionary correctly (they call their dictionary simply ‘hurricanes’), but they seem to redefine it again outside of the function by setting it equal to the function call.

Why is this necessary?


You are declaring (and later populating) the dictionary updated_hurricane_table within the scope of the combined_hurricane_data function. It can’t be seen outside the function unless you return it.

In your first screenshot, you make a function call

combined_hurricane_data(names, months, ... , deaths)

When the function is executed, a dictionary updated_hurricane_table will be created within the scope of the function. When you return it, the dictionary will be visible in the global scope. The name updated_hurricane_table means something within the function, but not outside the function. A dictionary is returned as a consequence of the function call, but if you don’t assign it to a variable, then it doesn’t accomplish anything. You created a dictionary, populated it, returned it and then just threw away the returned result.

Consider the following:

def f():
    x = [1, 2, 3]
    return x

# Function call (List is created and returned.
# The result is neither assigned to a variable nor is it printed, 
# so nothing useful happens).

# NameError 'x' is not defined
# Function call f() was made, but x is a list within the function's scope only.
# x doesn't mean anything outside the function regardless of the function call.

y = f()
# [1, 2, 3]
# The return value was assigned to the variable y.
# Name of variable is your choice. 
# Name of the variable in the global scope doesn't have to match the
# name of the variable you used within the function.
# x = f() is valid. y = f() is valid.


z = {"Cuba": 55, "Germany": 42}
print(z("Cuba")) # TypeError
print(z["Cuba"]) # 55

That makes good sense. Thank you :slightly_smiling_face:

1 Like