Could someone explain how the set.default and count[character] = count[character] + 1 works?

Viewed 69

So I'm working on some code in a course and I can't understand how the "count.setdefault" and "count[character] =" works. This code outputs how many times each letter has occurred in the messages string. I also don't understand how the message variable appears inside of an empty list "the count list". I know this is a bit to ask but I'm hoping I can get some helpful explanations from you guys.

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)

output:

{'I': 1, 't': 6, ' ': 13, 'w': 2, 'a': 4, 's': 3, 'b': 1, 'r': 5, 'i': 6, 'g': 2, 'h': 3, 'c': 3, 'o': 2, 'l': 3, 'd': 3, 'y': 1, 'n': 4, 'A': 1, 'p': 1, ',': 1, 'e': 5, 'k': 2, '.': 1}

From what I understood, the .setdefault works by assigning a value to a key if it doesn't exist in the list already and returns the second value after the comma if the key does exist already. Also this only works in the python console. Why?

1 Answers

You could find good explanation here - How does .setdefault() work?.

You will find it's equivalent method - collections.Counter, which can achieve same results more efficiently:

>>> from collections import Counter
>>> counts = Counter(message)
>>> counts == count   
     True 
 
Related