Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
questions about dict.get
#1
hi
in the below code:
 
#dict_get.py
print(help(dict.get))
'''
Help on method_descriptor:

get(self, key, default=None, /)
    Return the value for key if key is in the dictionary, else default.
'''
dict_1={'ali':12,"mohammad":15,"fatemeh":20}
dict_1.get('ali')
#12
dict_1.get('fatemeh')
#20
dict_1.get('fatemeh',default='40')       #line 14
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# TypeError: dict.get() takes no keyword arguments
dict_1.get('fatemeh','40')
20
dict_1.get('fatemeh440','40')
'40'
in help(dict.get), what are the meanings of self and / ?
in line 14, I want to use dict.get as in help(dict.get), but I am taken with an error(error message is commented in the above code) What is the problem?
in line 15, I omitted the default= from line 14, and I don't have the error message.
thanks for any guidance
Reply
#2
to get the value of a dictionary entry use dictname['key']
like:
>>> dict_1={'ali':12,"mohammad":15,"fatemeh":20}
>>> x = dict_1['fatemeh']
>>> x
20
or just:
>>> dict_1={'ali':12,"mohammad":15,"fatemeh":20}
>>> print(dict_1['ali'])
12
>>>
Reply
#3
self is the first argument to any instance method. It is the instance that called the method. In your example:
dict_1.get('ali')
"self" in get() would be dict_1.

/ in the argument list indicates that all arguments left of the / are position only arguments. This is why you got an error when trying to use the keyword "default". * is a similar delimiter. All arguments right of * are keyword only arguments. You can read about them here:

https://realpython.com/python-asterisk-a...arameters/
akbarza likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Sort a dict in dict cherry_cherry 4 78,139 Apr-08-2020, 12:25 PM
Last Post: perfringo
  Questions about elements in dict new_to_python 5 2,203 Feb-08-2020, 02:47 PM
Last Post: new_to_python
  Discord bot that asks questions and based on response answers or asks more questions absinthium 1 41,957 Nov-25-2017, 06:21 AM
Last Post: heiner55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020