0
What does get do in this code? I don't understand?
fib ={1:1, 2:1, 3:2, 4:3} print(fib.get(4,0) + fib.get(7,5))
2 Answers
+ 4
fib is a dictionary created there..
fib.get(key, defaultvalue) will return value at the key, if there is no key exists then it returns value as a defaultvalue.
So you get fb.get(4, 0) returns 3 , as 4 as key exist with value 3. [fb.get(4) =3]
fb.get(7, 5) returns 5 as there is no key 7 exist so output is 3+5=8
hope it clears..
+ 1
get prints the value key of the dictionary fib, but if the given key does not exist, as in the case of fib.get(7,5), then it prints its value 5.
dictionary.get(key, val)
This is necessary so that a compilation error does not occur, as is the case with the usual fib[7] output.