Why dict get key instead of dict key

0 votes

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:

dict = {"Name": "Harry", "Age": 17}
dict["Name"]
dict.get("Name")
Feb 18, 2022 in Python by Dev
• 6,000 points
427 views

No answer to this question. Be the first to respond.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
0 votes

As per the documentation the dictionary.get() is a built in method in Python and returns the value for key of it exists, else returns default.
dictionary.get(key, default=None, /)
 

For Example:

value = {"Name": "Harry", "Age": 17}
value["Name"]

Output

'Harry'
value.get("Name")

Output

'Harry'
value["Name"]

Output

'Harry'

When we try to access the key which is not present we get a key error.

value['Address']

Output

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-27-94bca0b4dfed> in <module>
----> 1 value['Address']

KeyError: 'Address'

using dictionary.get() 

value.get('Address', 'not mentioned')

Output

'not mentioned'
Hope this helps.
answered Feb 18, 2022 by Nandini
• 5,480 points

edited Mar 5

Related Questions In Python

0 votes
1 answer

Python join: why is it string.join(list) instead of list.join(string)?

950down voteaccepted It's because any iterable can be ...READ MORE

answered May 15, 2018 in Python by aryya
• 7,460 points
1,068 views
0 votes
1 answer

Python join: why is it string.join(list) instead of list.join(string)?

This is because join is a "string" ...READ MORE

answered Jul 30, 2018 in Python by Priyaj
• 58,020 points
952 views
0 votes
1 answer

Why is it string.join(list) instead of list.join(string)?

It's because any iterable can be joined ...READ MORE

answered Dec 2, 2020 in Python by Gitika
• 65,770 points
1,010 views
0 votes
1 answer

How can I get list of values from dict?

Here is an example to get the ...READ MORE

answered Feb 14, 2022 in Python by Nandini
• 5,480 points
1,365 views
0 votes
0 answers
0 votes
1 answer

Where can I get the list of Python keywords?

Just import a module “keyword”. Here you ...READ MORE

answered Apr 20, 2018 in Python by aayushi
• 750 points
769 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,679 views
0 votes
1 answer
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP