参见英文答案 >
Adding more than one value to dictionary when looping through string 7个
我需要构建一个函数,该函数将字符串作为输入并返回字典.
键是数字,值是包含具有等于键的字母数的唯一字的列表.
例如,如果输入函数如下:
n_letter_dictionary("The way you see people is the way you treat them and the Way you treat them is what they become")
该函数应返回:
{2: ['is'], 3: ['and', 'see', 'the', 'way', 'you'], 4: ['them', 'they', 'what'], 5: ['treat'], 6: ['become', 'people']}
我写的代码如下:
def n_letter_dictionary(my_string):
my_string=my_string.lower().split()
sample_dictionary={}
for word in my_string:
words=len(word)
sample_dictionary[words]=word
print(sample_dictionary)
return sample_dictionary
该函数返回字典如下:
{2: 'is', 3: 'you', 4: 'they', 5: 'treat', 6: 'become'}
字典不包含具有相同字母数的所有单词,但仅返回字符串中的最后一个单词.