返回字典 - 字符串中的单词长度 [英] Returning Dictionary-length of words in string
问题描述
我需要构建一个函数,作为输入字符串并返回一个字典。
键是数字,值是包含多个字母等于键
例如,如果输入函数如下:
I need to build a function that takes as input a string and returns a dictionary.
The keys are numbers and the values are lists that contain the unique words that have a number of letters equal to the keys.
For example, if the input function is as follows:
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
该函数返回一个字典,如下:
The function is returning a dictionary as follows:
{2: 'is', 3: 'you', 4: 'they', 5: 'treat', 6: 'become'}
字典不包含所有字母数字相同的字母但是只返回字符串中的最后一个。
The dictionary does not contain all the words with the same number of letters but is returning only the last one in the string.
推荐答案
由于您只想在 list
s,实际上使用集合
更有意义。您的代码几乎是正确的,您只需确保您创建一个集
如果字
不是一个键入您的字典,但如果字词
已经是您的字典中的关键字,则添加到集
中。以下显示如下:
Since you only want to store unique values in your list
s, it actually makes more sense to use a set
. Your code is almost right, you just need to make sure that you create a set
if words
isn't already a key in your dictionary, but that you add to the set
if words
is already a key in your dictionary. The following displays this:
def n_letter_dictionary(my_string):
my_string=my_string.lower().split()
sample_dictionary={}
for word in my_string:
words=len(word)
if words in sample_dictionary:
sample_dictionary[words].add(word)
else:
sample_dictionary[words] = {word}
print(sample_dictionary)
return sample_dictionary
n_letter_dictionary("The way you see people is the way you treat them and the Way you treat them is what they become")
输出
Output
{2: set(['is']), 3: set(['and', 'the', 'see', 'you', 'way']),
4: set(['them', 'what', 'they']), 5: set(['treat']), 6: set(['become', 'people'])}
这篇关于返回字典 - 字符串中的单词长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!