You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用for和if循环创建字典分组四字母单词时每个key仅存一个value的问题

错误原因

  • 你在首次创建字典key时,直接将单个单词字符串z赋值给了对应key,而非包裹了该单词的列表结构。
  • 后续执行append操作时,因为字符串类型没有append方法,会直接抛出属性错误,你看到每个key仅存一个值,本质是后续的追加操作都没有执行成功。

修正方案

方案1:修改原逻辑的初始赋值

只需要把首次赋值的代码改为存入列表即可:

dictionary = {}

for z in four_letters: #For each element of the four_letters list 
    last_letters = getLastLetters(z) #Get the last to letters from the word
    if last_letters not in dictionary: #If the last two letters have not already been made into a key in the dictionary...
        dictionary[last_letters] = [z] #Create a key and add the word as the first element of the value list
    else: #If it has...
        dictionary[last_letters].append(z) #Just add the word to the list of values

小优化:判断key是否存在不需要调用.keys()方法,直接写key in 字典即可,运行效率更高。

方案2:使用collections.defaultdict简化代码

可以省略手动判断key是否存在的逻辑,代码更简洁:

from collections import defaultdict

dictionary = defaultdict(list)
for z in four_letters:
    last_letters = getLastLetters(z)
    dictionary[last_letters].append(z)

内容的提问来源于stack exchange,提问作者Chloe Trickey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 15:54:10