Python Forum
questions about dict.get - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: questions about dict.get (/thread-41988.html)



questions about dict.get - akbarza - Apr-19-2024

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


RE: questions about dict.get - Larz60+ - Apr-19-2024

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
>>>



RE: questions about dict.get - deanhystad - Apr-19-2024

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-and-slash-special-parameters/