Reputation: 11
I'm learning python, now learning about dictionaries.
I think I understand it quite well, however I need help solving this code:
fib = {1: 1, 2: 1, 3: 2, 4: 3}
print(fib.get(4, 0) + fib.get(7, 5))
The answer of this is 8. But why? It should be 3 right? Because 7 and 5 dont even exist in the dictionary and it should return None.
Upvotes: 1
Views: 293
Reputation: 1
you can have a look over here the fib.get(7,7) is providing with the output of 7 as the second argument is considered to be default value it gives out 7 over there just like just above there fib.get(6,6) gives out 6 as an output. so when you provide fib.get(7,5) the second argument comes over there and gives out output adding with the value of first fib.get(4,3) which is 3 and final output of fib.get(4,0) +fib.get(7,5)] will be 8.. image makes you more clear
Upvotes: 0
Reputation: 35512
The second argument of get
is the default value: if the key isn't found, it'll return the second argument instead of None
. So, fib.get(7, 5)
will not find 7 and default to 5, leaving you with 3+5 which is 8.
Upvotes: 3