Trying to understand an error in Python

I don’t need to solve this problem, but to understand how Python thinks about a particular keystroke error I made.

So, I was trying to create a dictionary of characters in a string.

str1 = "Apple"
di = dict()

for char in str1:
    count = str1.count(char)
    di[char] += count

The code is incorrect because I have an iterator in the second to last line.
Python responded like this:

Traceback (most recent call last):
  File "c:\Users\Admin\Desktop\Desktop\PY4E\fcc_py\", line 6, in <module>
    di[char] += count
KeyError: 'A'

Now, KeyError means that a dictionary item could not be found.
I’m unsure how that error comes from a mistakenly placed iterator.
The way I understand it I am trying to add two unlike items: an integer and a key/value pair. In that case, the first charactyer ‘A’ would not be found because the two elements I’m trying to add are not copacetic.
Am I way off?

+= will try to get the value of di[char]. Since at the start di is empty, there’s no char key in it and KeyError is raised.


This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.