【发布时间】:2019-05-25 03:46:51
【问题描述】:
我正在尝试完成这个练习,我必须返回一个字典,其中键是单词的长度,值是单词本身。
预期的输出应该是这样的:
{3: ['May', 'and'], 4: ['your'], 6: ['Monday', 'coffee', 'strong'], 2: ['be'], 5: ['short']}
(可以按任何顺序)。但是,我不断得到一个输出,其中字典中的值列表不完整,例如:
{3: ['and'], 4: ['your'], 6: ['Monday'], 2: ['be'], 5: ['short']}
因为在使用 for 循环的第一次迭代后,它似乎停止向字典添加项目。
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']}
【问题讨论】:
标签: python list dictionary for-loop