python字典|'str' object has no attribute 'append'

如图,字典增加项目不就是dict[letter]=word 这个样的输入吗,问什么把word的中括号去掉,就会显示错误呢?words = ['apple', 'bat', 'bar', 'atom', 'book']dict={}for word in words: letter=word[0] if letter not in dict: dict[letter]=[word] else: dict[letter].append(word)
最新回答
绝绝子

2024-10-15 18:22:34

因为使用了append()方法,相当于需要指定字典A中A[letter]对应的值是列表。所以如果不加[]的话,是直接对字符串使用append(),会报错。
未明学院python课程助你入门数据分析和数据挖掘。
拾柒

2024-10-15 15:14:41

这是有问题的,根据你前面的定义A[letter]只是等于
字符串
,字符串没有append的方法,原来的[]是为了让她变为转化为数组list.