-3
word = input ('Enter a word: ')
vowels = {'a', 'e', 'i', 'o', 'u'}
results = {}

for c in word:
    if c in vowels:
        results[c] = results.get(c, 0)
        # results[c] = results.get(c, 0) + 1
for k, v in results.items():
    print (k, " is present", v, "times")

In the above code, I don't understand. what is the mean by -

results.get(c, 0) + 1

and what is the difference between?

results.get(c, 0) + 1 

results.get(c, 0)

at first, I thought that "results.get(c, 0) + 1" gives the output based on an empty dictionary, but when I executed this code "results.get(c, 0)", my understanding of get method got confused.

AamenIs
  • 81
  • 1
  • 1
  • 5
  • 2
    I'm not sure I understand your confusion. The different between `` and ` + 1` is that the second is the first plus 1. – Brian61354270 Aug 10 '23 at 01:07
  • my confusion is what does mean by this "results.get(c, 0) + 1"? – AamenIs Aug 10 '23 at 01:11
  • 1
    It gets the value of the dictionary entry with key `c`. If that key doesn't exit, it defaults to `0`. Then it adds `1` to that value. Finally, it stores that back into the dictionary element. – Barmar Aug 10 '23 at 01:14
  • So it adds 1 to `result[c]`, setting it to 1 the first time. – Barmar Aug 10 '23 at 01:15
  • 2
    Maybe you need to reread the documentation of `dict.get()` again to understand how the two arguments work. – Barmar Aug 10 '23 at 01:15
  • "but when I executed this code "results.get(c, 0)", my understanding of get method got confused." When you were confused by what happened, what was in `results` beforehand? What did you think the answer should be when you use that code on such a `results` input? What answer did you get instead, and how is that different? – Karl Knechtel Aug 10 '23 at 05:10

1 Answers1

0
results.get(c, 0)

returns the value of the key c in results. If the key doesn't exist, it returns 0.

results.get(c, 0) + 1 

returns the value of the key c in results and adds 1 to it. If the key doesn't exist, the value defaults to 0, it adds 1 to that, so the returned value of the entire expression is 1.

When you put it in the assignment

results[c] = results.get(c, 0) + 1

it adds 1 to results[c], but if the key doesn't already exist it sets it to 1.

So the code counts how many times each vowel appears in the string. The first time a particular vowel is encountered, it sets results[c] to 1, the following times it keeps adding 1 to it.

Barmar
  • 741,623
  • 53
  • 500
  • 612