sentence = "The quick brown fox jumped over the lazy dog."
characters = {}
for character in sentence:
characters[character] = characters.get(character, 0) + 1
print(characters)
I don’t understand what characters.get(character, 0) + 1 is doing, rest all seems pretty straightforward.
The
getmethod of a dict (like for examplecharacters) works just like indexing the dict, except that, if the key is missing, instead of raising aKeyErrorit returns the default value (if you call.getwith just one argument, the key, the default value isNone).So an equivalent Python function (where calling
myget(d, k, v)is just liked.get(k, v)might be:The sample code in your question is clearly trying to count the number of occurrences of each character: if it already has a count for a given character,
getreturns it (so it’s just incremented by one), elsegetreturns 0 (so the incrementing correctly gives1at a character’s first occurrence in the string).