Python:For循环在第一次迭代后停止向字典添加项目

标签 python list dictionary for-loop

我正在尝试完成这个练习,我必须返回一个字典,其中键是单词的长度,值是单词本身。

预期输出应该是这样的:

{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']}

最佳答案

对您的初始代码的一些评论

  • 每次执行dictionary[letter] = [word]时,您都会创建一个元素列表。
  • 相反,您希望通过执行 dictionary[letter].append(word) 将每个单词附加到列表中。

  • 您还可以使用 dict.setdefault 使用空列表实例化字典的每个键,并且仅添加列表中不存在的单词,以确保每个键的单词是唯一的

进行这些更改后,代码将起作用

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()

输出将是

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

关于Python:For循环在第一次迭代后停止向字典添加项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56301521/

相关文章:

python - 如何使用 NaN 对列进行 json_normalize

android - 可以连接多个 iBeacon

python - 为 rpy2 转换 python 对象

python - 列表理解 - 如果列表为空,则填充任意值

c# - 在没有 Foreach 循环的情况下更新列表的单列

python - 检查另一个字符串中的单词列表

arrays - 如何将数组或列表转换为 hashref?

python - 让 C 库使用 ctypes 调用 python 函数

python - 如何将数据插入 Django 用户模型?

python - 使用 cssselect 使用 lxml 获取 url