简体   繁体   中英

Can someone explain this dict().get function in Python?

I'm doing a coding challenge and this particular one is to return the original argument + the ordinal number. Examples:

return_end_of_number(553) ➞ "553-RD"

return_end_of_number(34) ➞ "34-TH"

return_end_of_number(1231) ➞ "1231-ST"

return_end_of_number(22) ➞ "22-ND"

Here is the top solution:

def return_end_of_number(num):
    d = {1: 'ST', 2: 'ND', 3: 'RD'}
    return '{}-{}'.format(num, d.get(num%10, 'TH'))

While my thinking of solving this problem was correct, I would of never thought of writing it this way. What are the elements of this part:

d.get(num%10, 'TH')

I see he/she is using num mod 10 to get the last digit, but is the 'TH' an argument to d.get to set a default value or something?

The interpreter shell is useful for answering such questions:

help(dict.get)

>>> get(self, key, default=None, /) 
>>> Return the value for key if key is in the dictionary, else default.

The num%10 just delivers the one's position number of any integer.

The dict.get(...) method takes an optional default argument: https://docs.python.org/3/library/stdtypes.html#dict.get

get(key[, default])

Return the value for key if key is in the dictionary, else default . If default is not given, it defaults to None , so that this method never raises a KeyError .

So, if we trace your example in the python repl:

>>> d = {1: 'ST', 2: 'ND', 3: 'RD'}

# Notice I'm not including the default argument
>>> d.get(3)
'RD'

# The key `4` doesn't exist.
>>> d.get(4) is None
True

# If we use a default for when the key doesn't exist
>>> d.get(4, 'this is the default value')
'this is the default value'
>>> d.get(4, 'TH')
'TH'

The get() method returns the value of the item with the specified key. Syntax

dictionary.get(keyname, value)

Here, the second argument value is optional. When you pass the second argument value, if the key is not found in the dictionary, it will return the 'value' which is passed as an argument.

For your solution, when key other than 1,2,3 given by (num%10) is searched using .get() method, then the second argument 'value' will be returned.

Reference: https://www.w3schools.com/python/ref_dictionary_get.asp

You're right, it's the default value!

dict[key] throws a KeyError if the key is not found:

>>> numbers = {'one':1, 'two':2, 'three':3}
>>> numbers['four']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'four'

dict.get(key) is nicer and returns the default None when the key is not found:

>>> numbers.get('four')
>>> 

However, if I wanted a custom default, I'd say dict.get(key, custom_default):

>>> numbers.get('four', 'not found')
'not found'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM