【问题标题】:Why do i get the TypeError "argument of type 'type' is not iterable"?为什么我得到 TypeError “类型'类型'的参数不可迭代”?
【发布时间】:2017-05-03 17:58:31
【问题描述】:

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

【问题讨论】:

    标签: python if-statement dictionary testing typeerror


    【解决方案1】:

    你的错误在这里:

    dictionary = dict
    

    这会创建对 type 对象 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 循环也有问题;以字符串形式循环为您提供单个字母,not 单词:

    >>> for word in "the quick":
    ...     print(word)
    ...
    t
    h
    e
    
    q
    u
    i
    c
    k
    

    如果你想要单词,你可以用str.split()分割空格:

    for word in sentence.split():
    

    【讨论】:

    • 您可能还想更改 for 循环以循环遍历句子而不是字母,正如我在上面添加的那样
    • @MarkBakker:已添加。
    • @MarkBakker:但是,这不需要是建议的编辑。本来可以对这个问题发表评论,但这里帖子的重点是确切的错误消息。
    • 非常感谢!我什至没有想到错误可能在那里。现在可以了!
    猜你喜欢
    • 1970-01-01
    • 2020-11-07
    • 2021-01-15
    • 2011-10-04
    • 2019-08-24
    • 2020-05-07
    • 2015-10-12
    • 1970-01-01
    相关资源
    最近更新 更多