0

I'm a beginner at Python and have tried to find an explanation for this but was unsuccessful.

Currently learning how to write a for loop to count occurrences of letters in a string (sentence) and returning the results in a dictionary. I'm following an online example.

This was the example:

message = "It was a bright cold day in April, and the birds were chirping."
count = {}

for character in message.upper():
    count.setdefault(character, 0) 
    count[character] = count[character] + 1

print(count)

I understand everything about it except

count[character] = count[character] + 1

As far as I can see, the count() function is normally formatted as:

string.count("XYZ") 

I think I understand why () brackets aren't used here, because

count(character) = count(character) +  1

doesn't make much sense, but I don't understand what

count[character]

is supposed to be doing - is it creating a list of each letter in the string and iterating through it? Is it creating/referencing an index?

Thank you!

  • Have you read this already? https://docs.python.org/3/tutorial/datastructures.html#dictionaries – mkrieger1 Apr 06 '21 at 23:26
  • I'll add that the `count` variable in this context is a dictionary (initialized by `count = {}` near the beginning of the code). `character` is the current character and so when the current character is 'A', for example, the loop is increasing the `count` for that entry by 1, with count['A'] = count['A'] + 1. If an entry for 'A' does not exist - the dictionary assumes a default of 0 (a result of your call to setdefault()) – BenWS Apr 06 '21 at 23:32

0 Answers0