为什么要得到TypeError“type'type'的参数不可iterable”?

2024-05-17 02:52:54 发布

您现在位置:Python中文网/ 问答频道 /正文

在测试了一些键是否已经存在之后,我正试图将它们添加到我的字典中。但每次我得到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)但也没用,所以我真的很困惑。


Tags: of代码indictionaryif字典typenot
1条回答
网友
1楼 · 发布于 2024-05-17 02:52:54

您的错误如下:

dictionary = dict

它创建对type对象dict的引用,而不是空字典。该类型对象确实不可iterable:

>>> 'foo' in dict
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument of type 'type' is not iterable

请改用{}

dictionary = {}

您也可以使用dict()(调用该类型以生成空字典),但首选{}语法(在代码片段中直观地扫描会更快、更容易)。

您的for循环也有问题;当string为您提供单独的字母时,循环会出现问题,而不是单词:

>>> for word in "the quick":
...     print(word)
...
t
h
e

q
u
i
c
k

如果您想要单词,可以使用str.split()在空白处分割:

for word in sentence.split():

相关问题 更多 >