Noneiffy04
Noneiffy04

Reputation: 135

Python: For loop stops adding items to a dictionary after first iteration

I am trying to complete this exercise where I have to return a dictionary where the key is the length of a word and the value is the word itself.

Expected output should be like this:

{3: ['May', 'and'], 4: ['your'], 6: ['Monday', 'coffee', 'strong'], 2: ['be'], 5: ['short']} 

(could be in any order). However, I keep getting an output where the list of values within the dictionary is incomplete, e.g:

{3: ['and'], 4: ['your'], 6: ['Monday'], 2: ['be'], 5: ['short']}

as it seems to stop adding items to the dictionary after the first iteration with the for loop.

def get_word_len_dict(text):
    dictionary = {}
    word_list = text.split()
    for word in word_list:
        letter = len(word)
        dictionary[letter] = [word]

    return dictionary

def test_get_word_len_dict():
    text = "May your coffee be strong and your Monday be short"
    the_dict = get_word_len_dict(text)
    print(the_dict) #should print {3: ['May', 'and'], 4: ['your'], 6: ['Monday', 'coffee', 'strong'], 2: ['be'], 5: ['short']}

Upvotes: 1

Views: 1216

Answers (1)

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20490

Some comments on your initial code

  • You are creating a single element list every time you do dictionary[letter] = [word].
  • Instead you would want to append each word to the the list by doing dictionary[letter].append(word).

  • You can also use dict.setdefault to instantiate each key of your dictionary with a empty list, and only add the word if not present in list to ensure the words are unique per key

After making these changes, the code will work

def get_word_len_dict(text):

    #Instantiate your dictionary
    dictionary = {}
    word_list = text.split()

    for word in word_list:
        letter = len(word)

        #Set default value of key as a list
        dictionary.setdefault(letter,[])

        #If the word is not present in the list, only then add it
        if word not in dictionary[letter]:
            dictionary[letter].append(word)

    return dictionary

def test_get_word_len_dict():
    text = "May your coffee be strong and your Monday be short"
    the_dict = get_word_len_dict(text)

    print(the_dict)

test_get_word_len_dict()

The output will be

{3: ['May', 'and'], 4: ['your'], 6: ['strong', 'coffee', 'Monday'], 2: ['be'], 5: ['short']}

Upvotes: 1

Related Questions