+ 1
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)) the answer derived was 8 !?? How??
Need explanation please"" I'm having a lot of difficulty in finding how did the program derive these answer
4 Respuestas
+ 2
fib is a dictionary.
dictionary objects do have a get() method that works like this:
syntax:
dict.get(element, fallback)
if element is a key in the dictionary return its value if not return the fallback value
In the print statement are two cases:
fib.get(4, 0) will return 3 because there is a key 4 and its value is 3
fib.(7, 5) returns 5 because there is no key 7 in fib so it returns the fallback
So we get:
>>> print(3 + 5)
8
0
so if fib.get (4,0) returns 3 which is on position 0 (array like term looking at if it were something like 4:{3,5,8,5} ) then the dictionary 7 with position 5 has a value of 5 by default?
0
Hello again @thomo,
@thomo I believe you are confusing dictionary with array.
They are not the same thing. A dictionary is composed of key and value pairs.
for example in fib you get:
key value
------------------
fib = { 1 : 1
2 : 1
3 : 2
4 : 3 }
when you use in the fib.get() method you provide a key as first argument.
fib.get(4) returns the value associated with key 4, that is 3.
The second argument to this method is optional.
Normally, if the key you provide to the get() method is not in the dictionary, like
in fib.get(7) the return value would be None.
BUT when you pass the second argument if the key is not found in the dictionary
THE SECOND ARGUMENT IS RETURNED like in fib.get(7, 5) -- it returns 5.
0
Thank you for the explanation! It helped. I must have missed the "syntax: dict.get(element, fallback)" Thank you!