0

Dictionaries in python

if I have: fib = {1:1,2:1,3:2,4:3} print(fib.get(4,0) + fib.get(7,5) I thought the fib.get(4,0) would change the value of key 4 to 0. Instead I get the output 8, can anyone elaborate a little more about this please?

20th May 2019, 12:06 AM
Julio Eduardo Paiz Bobadilla
Julio Eduardo Paiz Bobadilla - avatar
2 Respuestas
+ 3
The function dict.get(key, default=None) returns the value associated with key if the dictionary has the key or default if it does not exists That's why, when you write fib.get(4,0), it returns 3, the key 4 exists and so, it returns its value 3 For fib.get(7,5), 7 is not a valid key, thus it returns the default which is 5
20th May 2019, 12:35 AM
Paul
0
Thank you very much!
20th May 2019, 3:52 AM
Julio Eduardo Paiz Bobadilla
Julio Eduardo Paiz Bobadilla - avatar