pythondictionary

Not understanding a trick on .get() method in python


While learning python I came across a line of code which will figure out the numbers of letters.

dummy='lorem ipsum dolor emet...'
letternum={}

for each_letter in dummy:
    letternum[each_letter.lower()]=letternum.get(each_letter,0)+1

print(letternum)

Now, My question is -in the 4th line of code inletternum.get(each_letter,0)+1 why there is ,0)+1and why is it used for. Pls describe.


Solution

  • The get method on a dictionary is documented here: https://docs.python.org/3/library/stdtypes.html#dict.get

    get(key[, default])

    Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

    So this explains the 0 - it's a default value to use when letternum doesn't contain the given letter.

    So we have letternum.get(each_letter, 0) - this expression finds the value stored in the letternum dictionary for the currently considered letter. If there is no value stored, it evaluates to 0 instead.

    Then we add one to this number: letternum.get(each_letter, 0) + 1

    Finally we stored it back into the letternum dictionary, although this time converting the letter to lowercase: letternum[each_letter.lower()] = letternum.get(each_letter, 0) + 1 It seems this might be a mistake. We probably want to update the same item we just looked up, but if each_letter is upper-case that's not true.