0 votes
1 view
in Python by (47.8k 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 (107k 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

+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.8k points)
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...