Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 928
Zuhair Abid Avatar asked Apr 24 '26 07:04

Zuhair Abid


2 Answers

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.

like image 50
Weeble Avatar answered May 05 '26 13:05

Weeble


letternum is a dict (a dictionary). It has a method called get which returns the value associated with a given key. If the key is absent from the dictionary, it returns a default value, which is None unless an optional second argument is present, in which case that argument value is returned for missing elements.

In this case, letternum.get(each_letter,0) returns letternum[each_letter] if each_letter is in the dictionary. Otherwise it returns 0. Then the code adds 1 to this value and stores the result in letternum[each_letter.lower()].

This creates a count of the number of occurrences of each letter, except that it inconsistently converts the letter to lowercase when updating, but not when retrieving existing values, so it won't work properly for uppercase letters.

like image 25
Tom Karzes Avatar answered May 05 '26 13:05

Tom Karzes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!