在测试了一些键是否已经存在之后,我正试图将它们添加到我的字典中。但每次我得到TypeError "argument of type 'type' not iterable
时,我似乎都做不到测试。
这基本上是我的代码:
dictionary = dict
sentence = "What the heck"
for word in sentence:
if not word in dictionary:
dictionary.update({word:1})
我也试过if not dictionary.has_key(word)
但也没用,所以我真的很困惑。
您的错误如下:
它创建对type对象
dict
的引用,而不是空字典。该类型对象确实不可iterable:请改用
{}
:您也可以使用
dict()
(调用该类型以生成空字典),但首选{}
语法(在代码片段中直观地扫描会更快、更容易)。您的
for
循环也有问题;当string为您提供单独的字母时,循环会出现问题,而不是单词:如果您想要单词,可以使用
str.split()
在空白处分割:相关问题 更多 >
编程相关推荐