Python Dictionary (Get Method) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Python Dictionary (Get Method)

Why does the answer of this question is 8?? What is the result of this code? fib = {1: 1, 2: 1, 3: 2, 4: 3} print(fib.get(4, 0) + fib.get(7, 5))

18th Feb 2019, 3:54 AM
John Mark
John Mark - avatar
1 Answer
+ 3
The result is 8 because get retrieves the value at the key specified in the first argument if it exists, otherwise it returns the argument specified in the second argument, or None, if the argument is not present. So in the print statement fib.get(4,0) returns 3 (value at key 4), and fib.get(7,5) returns 5 (no value at key 7). These add up to 8.
18th Feb 2019, 4:05 AM
Kinshuk Vasisht
Kinshuk Vasisht - avatar