0

get() in Python Dictionary

i am just getting stucked in get() method. can anyone explain me how this method works. i didn't understand this get() method.

23rd Jul 2020, 10:17 AM
Mr. 12
Mr. 12 - avatar
4 odpowiedzi
+ 7
It tries to obtain a value for that key and if the key isn't in the dictionary then it returns whatever you pass as a second argument (None by default), used to avoid errors: fruits = {"apple": 2, "banana": 3} value = fruits.get("pear", 0) print(value) # 0 It returns 0 as passed in the 2nd argument, however it'd return apple plenty actual value if pear was in the fruits dictionary
23rd Jul 2020, 10:21 AM
Bagon
Bagon - avatar
+ 5
a = {1:"one",2:"two",3:"three"} print(a.get(4,"four")) print(a.get(3,"five")) Output: four three The already existing values will not change But the values which are not there in the dictionary will give the output as it is! And if you try to print the value of a It has not changed!
23rd Jul 2020, 12:04 PM
Namit Jain
Namit Jain - avatar
+ 3
the first parameter is the key youre looking for in the dictionary. The second param is what to return if the key is not found. Helps save your program from fatal errors if a non-existant key is searched
23rd Jul 2020, 10:20 AM
Slick
Slick - avatar
+ 2
Now I Get It, Thank You All Guys
23rd Jul 2020, 5:04 PM
Mr. 12
Mr. 12 - avatar