0

Dictionary question from lesson

it gets the 3 from position 4, but returns a 5 for position 7 as it's not set? right?

28th Feb 2018, 6:17 PM
Nils Kaplan
Nils Kaplan - avatar
6 odpowiedzi
+ 1
python dictionary get method returns a value of the given key is present, otherwise it returns default value that you supply. d.get(4,0) returns d[4] if 4 is present as a key, otherwise it returns zero. if you directly access d[4], you will get a key error is if key is not present in the dictionary.
28th Feb 2018, 7:13 PM
Ravi Chandra Enaganti
Ravi Chandra Enaganti - avatar
+ 17
In Python get method work like this... get(key , value by defalut) so if the key is present in the dictionary it will return it's value but if it is not present it uses the default value provided... for eg: In ur case the dictionary must be having key 4 but key 7 will not be there in the dictionary... so what ur saying is happening....😀
28th Feb 2018, 7:17 PM
🌛DT🌜
🌛DT🌜 - avatar
+ 2
Possibly. Hard to say without seeing what you're seeing. Post up your code if you don't mind. Most languages would give you an "index out of range" error, but I can't remember if Python does that or not, or if it simply grabs the last element. I haven't read Python documentation since Python 2 and that was ages ago now so my memory gets the best of me. If I can see the code though, I can tell you with 100% certainty.
28th Feb 2018, 6:25 PM
Fata1 Err0r
Fata1 Err0r - avatar
0
it was the lesson introducing dictionaries in python 3, print(dic.get(4,0)+dic.get(7,5) I think something like that... (my hands are so cold)
28th Feb 2018, 6:38 PM
Nils Kaplan
Nils Kaplan - avatar
0
thanks ravi, just making sure!
28th Feb 2018, 7:14 PM
Nils Kaplan
Nils Kaplan - avatar
0
thanks DT!
28th Feb 2018, 7:18 PM
Nils Kaplan
Nils Kaplan - avatar