spi*_*tty 2 python testing dictionary if-statement 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})
Run Code Online (Sandbox Code Playgroud)
我也试过,if not dictionary.has_key(word)
但它也没用,所以我真的很困惑.
你的错误在这里:
dictionary = dict
Run Code Online (Sandbox Code Playgroud)
这会创建对类型对象 的引用dict
,而不是空字典.该类型对象确实不可迭代:
>>> 'foo' in dict
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument of type 'type' is not iterable
Run Code Online (Sandbox Code Playgroud)
{}
改为使用:
dictionary = {}
Run Code Online (Sandbox Code Playgroud)
您也可以使用dict()
(调用该类型来生成空字典),但{}
语法是首选的(在一段代码中以可视方式扫描更快更容易).
你的for
循环也有问题; 循环作为字符串给你单独的字母,而不是单词:
>>> for word in "the quick":
... print(word)
...
t
h
e
q
u
i
c
k
Run Code Online (Sandbox Code Playgroud)
如果你想要单词,你可以在空格上拆分str.split()
:
for word in sentence.split():
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
15261 次 |
最近记录: |