2

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?

  • See [the docs](https://docs.python.org/3/library/stdtypes.html#dict.setdefault). – ssp Dec 04 '20 at 02:26
  • Your understanding is already correct, so it's unclear what you *don't* understand here. As for only working in the Python console (REPL?) it works just fine anywhere; not sure why you think it wouldn't work in a script. Side-note: In this case, `setdefault` doesn't really do much. You could just as easily replace both lines in the loop with just `count[character] = count.get(character, 0) + 1` (`get` could be `setdefault`, it doesn't matter much since you assign to it anyway, and `get` is shorter to type). – ShadowRanger Dec 09 '20 at 02:59
  • Note: Even if this isn't a precise duplicate, your question needs a lot more focus. You're basically asking us to "explain every single thing in very simple code", and that's 4+ questions by my count. – ShadowRanger Dec 09 '20 at 03:01

1 Answers1

0

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 
 
Daniel Hao
  • 4,922
  • 3
  • 10
  • 23