Creating a dictionary where the key is an integer and the value is the length of a random phrase

advertisements

Super new to to python here, I've been struggling with this code for a while now. Basically the function returns a dictionary with the integers as keys and the values are all the words where the length of the word corresponds with each key.

So far I'm able to create a dictionary where the values are the total number of each word but not the actual words themselves.

So passing the following text

"the faith that he had had had had an affect on his life"

to the function

def get_word_len_dict(text):
    result_dict = {'1':0, '2':0, '3':0, '4':0, '5':0, '6' :0}
    for word in text.split():
        if str(len(word)) in result_dict:
            result_dict[str(len(word))] += 1
    return result_dict

returns

1 - 0
2 - 3
3 - 6
4 - 2
5 - 1
6 - 1

Where I need the output to be:

2 - ['an', 'he', 'on']
3 - ['had', 'his', 'the']
4 - ['life', 'that']
5 - ['faith']
6 - ['affect']

I think I need to have to return the values as a list. But I'm not sure how to approach it.


I think that what you want is a dic of lists.

result_dict = {'1':[], '2':[], '3':[], '4':[], '5':[], '6' :[]}
for word in text.split():
    if str(len(word)) in result_dict:
        result_dict[str(len(word))].append(word)
return result_dict