Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding .get() method in Python [duplicate]

Tags:

python

sentence = "The quick brown fox jumped over the lazy dog." characters = {}  for character in sentence:     characters[character] = characters.get(character, 0) + 1   print(characters) 

I don't understand what characters.get(character, 0) + 1 is doing, rest all seems pretty straightforward.

like image 266
eozzy Avatar asked Jan 14 '10 23:01

eozzy


People also ask

How does get () work in Python?

get() method is used in Python to retrieve a value from a dictionary. dict. get() returns None by default if the key you specify cannot be found. With this method, you can specify a second parameter that will return a custom default value if a key is not found.

How does Dict get work?

get() method returns: the value for the specified key if key is in the dictionary. None if the key is not found and value is not specified. value if the key is not found and value is specified.

What does Items () do in Python?

Python Dictionary items() Method The items() method returns a view object. The view object contains the key-value pairs of the dictionary, as tuples in a list. The view object will reflect any changes done to the dictionary, see example below.


2 Answers

The get method of a dict (like for example characters) works just like indexing the dict, except that, if the key is missing, instead of raising a KeyError it returns the default value (if you call .get with just one argument, the key, the default value is None).

So an equivalent Python function (where calling myget(d, k, v) is just like d.get(k, v) might be:

def myget(d, k, v=None):   try: return d[k]   except KeyError: return v 

The sample code in your question is clearly trying to count the number of occurrences of each character: if it already has a count for a given character, get returns it (so it's just incremented by one), else get returns 0 (so the incrementing correctly gives 1 at a character's first occurrence in the string).

like image 157
Alex Martelli Avatar answered Oct 11 '22 21:10

Alex Martelli


To understand what is going on, let's take one letter(repeated more than once) in the sentence string and follow what happens when it goes through the loop.

Remember that we start off with an empty characters dictionary

characters = {} 

I will pick the letter 'e'. Let's pass the character 'e' (found in the word The) for the first time through the loop. I will assume it's the first character to go through the loop and I'll substitute the variables with their values:

for 'e' in "The quick brown fox jumped over the lazy dog.":     {}['e'] = {}.get('e', 0) + 1  

characters.get('e', 0) tells python to look for the key 'e' in the dictionary. If it's not found it returns 0. Since this is the first time 'e' is passed through the loop, the character 'e' is not found in the dictionary yet, so the get method returns 0. This 0 value is then added to the 1 (present in the characters[character] = characters.get(character,0) + 1 equation). After completion of the first loop using the 'e' character, we now have an entry in the dictionary like this: {'e': 1}

The dictionary is now:

characters = {'e': 1} 

Now, let's pass the second 'e' (found in the word jumped) through the same loop. I'll assume it's the second character to go through the loop and I'll update the variables with their new values:

for 'e' in "The quick brown fox jumped over the lazy dog.":     {'e': 1}['e'] = {'e': 1}.get('e', 0) + 1 

Here the get method finds a key entry for 'e' and finds its value which is 1. We add this to the other 1 in characters.get(character, 0) + 1 and get 2 as result.

When we apply this in the characters[character] = characters.get(character, 0) + 1 equation:

characters['e'] = 2 

It should be clear that the last equation assigns a new value 2 to the already present 'e' key. Therefore the dictionary is now:

characters = {'e': 2} 
like image 26
zeyad elharabi Avatar answered Oct 11 '22 19:10

zeyad elharabi