[get] method in dictionary | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

[get] method in dictionary

Can anyone please help to explain for the result of this example: figure = {1: 1, 2: 1, 3: 2, 4: 3} print(figure.get(4,0)+figure.get(7,5)) Why the result is 8? Thank you.

27th Aug 2020, 8:07 AM
Lili
Lili - avatar
1 Answer
+ 2
The `get` method accepts two parameters. The first one is mandatory, it represents a dictionary key. `get` method tries to find an item associated with that key inside the dictionary. If found, the value of the matching item is returned, otherwise `None` will be returned. The second parameter is optional, if something was passed for the second parameter, then `get` method will return it in case there is no item was found to be associated with such key (given for first parameter). get(4, 0) succeeded, cause there is an item associated with key 4. Here `get` method returns 3. get(7, 5) fails, cause there is no item found to be asociated with key 7. Here `get` method returns 5 (the second argument passed to `get` method). Now add them up (3 + 5), voila!
27th Aug 2020, 8:32 AM
Ipang