Hurricane Analysis Step 4

I am not sure how to build on a list that is a value in a dictionary. The code I have works all the way through the

if current_year not in new_dictionary:
      new_dictionary[current_year] = current_cane

(I’ve checked by printing), but it fails the else. Here’s what I have:

def convert_dictionary(dictionary, key_word, key_list):
  new_dictionary = {}
  for entry in dictionary:
    current_year = dictionary[entry][key_word]
    current_cane = dictionary[entry]
    if current_year not in new_dictionary:
      new_dictionary[current_year] = current_cane
    else:
      new_dictionary[current_year].append(current_cane)
  return new_dictionary


  
year_dictionary = convert_dictionary(name_dictionary, "Year", years_no_repeats)
print(year_dictionary)

The instructions are to build a dictionary with hurricane years as the keys and the dictionary associated with those years as the values.
Could anyone offer how to complete the else?

It’s tricky to do this without pre-populating the dictionary, since this problem pops up quite often though there are a few in-built ways around it. Have a look into collections.defaultdict or the .setdefault method of a dictionary.

I think you might have an easier time if every value was a list though, even if it only contained a single element. Inconsistent types are harder to work with (if you wrote a function that accepts the output of this function should it work with dictionary values or list values…?). That kind of thing is also likely to confuse the next person who comes along too. If you can think long-term maintenance/readability then the consistent types will probably trump saving the creation of a few extra lists.