def count_chars(s):
'''Return a dict that contains each character in str s as a key. The
value associated with each key is the number of times that character
occurs in s.'''
d = {}
for ch in s:
if ch in d:
d[ch] += 1
else:
d[ch] = 1
return d
I don’t get the 3rd line in the code, “if ch in d”. Why would the character be in the dictionary if it does not have any entries in the dic yet?
Also, I don’t get what d[ch] += 1 is supposed to mean, and why there would be an else statement. Can someone please help me?
The easiest way to understand code like this is to add
prints to see what it is actually doing. So,tells you: