Back

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

Today, I came across the dict method get which, given a key in the dictionary, returns the associated value.

For what purpose is this function useful? 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 (106k points)
edited by

We use dict.get(key) instead of dict[key] because It allows you to provide a default value if the key is missing:-

dictionary.get("bogus", default_value)

The above code returns default_value (whatever you choose it to be).

Whereas when you use dict[key]:-

dictionary["bogus"]

It would raise a KeyError.

To know more about this you can have a look at the following video tutorial:-

Related questions

0 votes
1 answer
asked Feb 16, 2021 in Python by ashely (50.2k points)
+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)
0 votes
1 answer

Browse Categories

...