Reputation: 41
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.
Upvotes: 4
Views: 60742
Reputation: 1124000
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():
Upvotes: 9