Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

Look at the below code:

sentence = "The quick brown fox jumped over the lazy dog."

characters = {}

for character in sentence:

    characters[character] = characters.get(character, 0) + 1 

print(characters)

In the above code, I didn't understand what does characters.get(character, 0) + 1 is doing, rest I can understand.

Anyone, please help me!

1 Answer

0 votes
by (26.4k points)

The get method for a dict (like for instance characters) works much the same as ordering the dict, then again, actually, if the key is absent, rather than raising a KeyError it restores the default value (in the event that you call .get with only one contention, the key, the default value is None). 

So a comparable Python function (where calling myget(d, k, v) is much the same as d.get(k, v) may be: 

def myget(d, k, v=None):

  try: return d[k]

  except KeyError: return v

The example code in your inquiry is clearly attempting to check the quantity of events of each character: on the off chance that it as of now has a mean a given character, get returns it (so it's only augmented by one), else get returns 0 (so the increasing effectively gives 1 at a character's first event in the string).

Looking for python tutorial certification course? Join Python course fast!!

Watch this video tutorial on how to become a professional in python course:

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...