Last answered:

14 Feb 2022

Posted on:

06 Nov 2021

0

Python dictionary time 9:21

can u please explain why is there a +1 after .get fucntion ?

3 answers ( 0 marked as helpful)
Instructor
Posted on:

08 Nov 2021

1

Hey Wahab,

Thank you for your question!

The purpose of this dictionary is to store all characters appearing in the text as keys and their count as values. That is to say, we want to keep a count of each character in the text. Let's examine the for-loop. The iterator called letter goes through each letter in the text. Let us assume the letter is 'M' and that we encounter it for the third time. This means we want to change the value of letter_count['m'] from 2 to 3. This update we perform with the help of letter_count.get('m', 0) + 1.The get() method returns the current value of letter_count['m'] which is 2. We add one to this value to account for the fact that we have encountered the letter 'm' for the third time in the text.

Hope this helps!

Kind regards,
365 Hristina

Posted on:

08 Nov 2021

1

Look, if we go through beginning considering letter 'm' then after 1st iteration m would be considered as key of the dictionary which would receive a value from get method
now get has a default return type as 'noneType' which cannot be added with 1 so instead we placed a '0' as return value (you can type 'type(dict.get)' in console to know more about get function)
so now In 1st Iteration if the get function would return value as '0' (and lets suppose 1 is not there) then in 2nd iteration whenever m appears as key get would return its present value as 0 but we know that 'm' has already appeared once
Now add 1 to equation and repeat all the steps. So, that '1' is necessasry to keep the counter going. Hope this helps

Posted on:

14 Feb 2022

6

I found this to be confusing, but after critical thinking, i think i should make this contribution:
Remember our initial declaration of dictionary i.e. Letter_count = { }
has nothing in it, so all letters will initially have zero i.e. the default integer values right?
Good!
But after the first iteration, say we pick letter = a, we must update our dictionary to count for a, so the dict[key] = value

Letter_count[letter.lower()] = Letter_count.get(letter,0) + 1



so the Letter_count.get(letter,0) part indicates the initial value from the empty dictionary, while
the 1 indicates that i have seen the letter a once, so adding it to 0 automatically give the value of that key an interger of 1.
So for the first loop, using letter a as example, we now have something like:

Letter_count["a"] = 1

so the second loop will get the value of letter "a" to be 1, then adding the 1 to it again will make it 2.

I hope this helps!!!

Submit an answer