简体   繁体   中英

Why do i get the TypeError “argument of type 'type' is not iterable”?

I am trying to add some keys to my dictionary after testing if they are already existing keys. But I seem not to be able to do the test, every time I get the TypeError "argument of type 'type' not iterable .

This is basically my code:

dictionary = dict
sentence = "What the heck"
for word in sentence:
      if not word in dictionary:
             dictionary.update({word:1})

I also tried if not dictionary.has_key(word) but it didn't work either so I am really confused.

Your error is here:

dictionary = dict

That creates a reference to the type object dict , not an empty dictionary. That type object is indeed not iterable:

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

Use {} instead:

dictionary = {}

You could also have used dict() (calling the type to produce an empty dictionary), but the {} syntax is preferred (it is faster and easier to scan for visually in a piece of code).

You also have an issue with your for loop; looping over as string gives you the individual letters, not words:

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

q
u
i
c
k

If you wanted words, you could split on whitespace with str.split() :

for word in sentence.split():

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM