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.
4 Answers
+ 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
+ 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!
+ 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
+ 2
Now I Get It, Thank You All Guys