为什么我得到类型'类型'的TypeError"参数?不可迭代"?

时间:2016-12-18 15:17:17

标签: python if-statement dictionary testing typeerror

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

1 个答案:

答案 0 :(得分:5)

您的错误在这里:

dictionary = dict

这会创建对类型对象 dict的引用,而不是空字典。该类型对象确实不可迭代:

>>> '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循环也存在问题;循环作为字符串为您提供单独的字母,字:

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

q
u
i
c
k

如果您想要单词,可以使用str.split()

分割空白
for word in sentence.split():