Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I was working on dictionary format data and I came across the dict function, named get(). In that function, if we provide a key in the dictionary, it will return the associated value.

I want to know the usage of this function. If I wanted to find a value associated with a key in a dictionary, I can just do dict[key], and it returns the same thing:

dictionary = {"Name": "Harry", "Age": 17}

dictionary["Name"]

dictionary.get("Name")

1 Answer

0 votes
by (108k points)

Kindly be informed that the get() function will help you to provide a default value if the key-value is not there:

dictionary.get("bogus", default_value)

returns default_value (whatever you choose it to be), whereas

dictionary["bogus"]

It will give you some KeyError.

If you are not using that function, then the default_value is None, like:

dictionary.get("bogus")  # <-- No default specified -- defaults to None

dictionary.get("bogus", None)

Want to become a Python Developer? Check out this insightful Python Certification course.

Related questions

0 votes
1 answer
asked Jul 4, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Oct 3, 2019 in Python by Sammy (47.6k points)
0 votes
2 answers
+1 vote
1 answer
asked Jul 5, 2019 in Python by selena (1.6k points)
0 votes
1 answer
asked Oct 11, 2019 in Python by Sammy (47.6k points)

Browse Categories

...