The line of code below is meant to count the number of individual letters in the sentence assigned to the variable "message".
message = 'It was a bright cold day in April, and the clocks were striking thirteen'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] 1
print(count)
The code runs successfully with the output below
{' ': 13, ',': 1, '.': 1, 'A': 1, 'I': 1, 'a': 4, 'c': 3, 'b': 1, 'e': 5, 'd': 3, 'g': 2,
'i': 6, 'h': 3, 'k': 2, 'l': 3, 'o': 2, 'n': 4, 'p': 1, 's': 3, 'r': 5, 't': 6, 'w': 2, 'y': 1}
Please what is this part of the code doing in the program
count[character] = count[character] 1
CodePudding user response:
The line of code you mention in your question:
- Extracts the existing dictionary value for the given key (character) and increments it by 1
count[character] 1
. - Updates the value for the key
count[character] =
.
You may actually make your code a bit shorter as setdefault method returns the current value for a given key:
message = 'It was a bright cold day in April, and the clocks were striking thirteen'
count = {}
for character in message:
count[character] = count.setdefault(character, 0) 1
print(count)
CodePudding user response:
count[character] = count[character] 1
is essentially increasing the count of the current character by one. So, first of all, setdefault()
is a function that checks if the current count exists in the dictionary. If it doesn't, it will be added with the default value of 0. Then in the dictionary, that character will be incremented by one. Let me give an example. If we are on the first (zeroth) character in message
, 'I', setdefault()
checks if 'I' is already in the dictionary, then adds it with the value of 0. Then it is incremented by one. That means the value of 'I' in the dictionary is now 1
.