Advanced-python-code-challenges-dictionaries

Challenge:
Write a function named frequency_dictionary that takes a list of elements named words as a parameter. The function should return a dictionary containing the frequency of each element in words .

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

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

Mine returned different result than Codecademys’. I’m not sure what went wrong at the else statement.

Thank you!

To preserve code formatting in forum posts, see: [How to] Format code in posts

In the Codecademy solution code:

  • If a word is not already present in the results dictionary, then a new entry (key) is created with an initial vaue of 0 and then in the same iteration of the loop, the value is incremented because of the statement freqs[word] += 1.

  • If a word is already present in the results dictionary, then it is incremented because of the statement freqs[word] += 1.

In the Codecademy solution code, the freqs[word] += 1 statement is being executed in every single iteration of the loop.

In your attempted solution code:

  • If a word is not already present in the results dictionary, then a new entry (key) is created with an initial vaue of 0 and then in the same iteration of the loop, the value is incremented because of the statement word_length[word] += 1. (The strike-through part doesn’t get executed because the increment statement is in the else block).

  • If a word is already present in the results dictionary, then it is incremented because of the statement word_length[word] += 1.

If you wish to use an if-else structure to implement the logic, you could do:

if word not in word_length:
    word_length[word] = 1
else:
    word_length[word] += 1

This way, a new entry will be created with an initial value of 1.

2 Likes

Understood. Thank you so much for your explanation, appreciate it :slight_smile:

1 Like