Python Code Challenges - Dictionaries (Advanced), Frequency Count

Hello,

Could someone help me understand a part of this question? The prompt:

This next function is similar, but instead of counting the length of each string in the list of strings, we will be counting the frequency of each string. This function will also accept a list of strings as input and return a new dictionary. Here is what we need to do:

  1. Define the function to accept one parameter for our list of strings
  2. Create a new empty dictionary
  3. Loop through every string in the list of strings
  4. Inside the loop, if the string is not already in our dictionary, store the string as a key with a value of 0 in our dictionary. Then, increment the value by 1.
  5. After the loop, return the new dictionary

My code:

def frequency_dictionary(words):
  new_dict = {}
  for word in words:
    if word not in new_dict:
      new_dict[word] = 0
    new_dict[word] += 1
  return new_dict

print(frequency_dictionary(["apple", "apple", "cat", 1]))
# should print {"apple":2, "cat":1, 1:1}
print(frequency_dictionary([0,0,0,0,0]))
# should print {0:5}

The listed instructions tell us to store the string as a key with a value of ‘0’ if not already in the new dictionary. However, the hint tells us to do the same but with a value of ‘1’, which makes more sense to me. Since it is the first instance of the word appearing, shouldn’t we start that initialization’s value at 1?

The hint:

HintFirst, create a new empty dictionary. Then, loop through every word in words. If word is not a key in the dictionary, make word a key with a value of 1. If word was already a key, increase the value associated with word by 1.

Thank you!

You could start by initializing with a count of 1, but then you’d need an else.