今天,我遇到了dict方法get,它在字典中给定一个键,返回相关的值。

这个函数的用途是什么?如果我想在字典中找到一个与键相关的值,我可以只做dict[key],它返回相同的东西:

dictionary = {"Name": "Harry", "Age": 17}
dictionary["Name"]
dictionary.get("Name")

当前回答

有一个区别,这可能是一个优势,如果我们正在寻找一个不存在的键,我们将得到None,不像我们使用括号符号时,在这种情况下,我们将得到一个错误抛出:

print(dictionary.get("address")) # None
print(dictionary["address"]) # throws KeyError: 'address'

get方法最后一个很酷的地方是,它接收了一个额外的可选参数作为默认值,也就是说,如果我们试图获取学生的分数值,但学生没有分数键,我们可以得到0。

所以与其这样做(或类似的事情):

score = None
try:
    score = dictionary["score"]
except KeyError:
    score = 0

我们可以这样做:

score = dictionary.get("score", 0)
# score = 0

其他回答

它允许你在缺少键时提供一个默认值:

dictionary.get("bogus", default_value)

返回default_value(不管你选择它是什么),而

dictionary["bogus"]

会引发一个KeyError。

如果省略,default_value为None,这样

dictionary.get("bogus")  # <-- No default specified -- defaults to None

返回None

dictionary.get("bogus", None)

会。

有一个区别,这可能是一个优势,如果我们正在寻找一个不存在的键,我们将得到None,不像我们使用括号符号时,在这种情况下,我们将得到一个错误抛出:

print(dictionary.get("address")) # None
print(dictionary["address"]) # throws KeyError: 'address'

get方法最后一个很酷的地方是,它接收了一个额外的可选参数作为默认值,也就是说,如果我们试图获取学生的分数值,但学生没有分数键,我们可以得到0。

所以与其这样做(或类似的事情):

score = None
try:
    score = dictionary["score"]
except KeyError:
    score = 0

我们可以这样做:

score = dictionary.get("score", 0)
# score = 0

另一个我没有看到提到的用例是作为sort, max和min等函数的key参数。get方法允许根据它们的值返回键。

>>> ages = {"Harry": 17, "Lucy": 16, "Charlie": 18}
>>> print(sorted(ages, key=ages.get))
['Lucy', 'Harry', 'Charlie']
>>> print(max(ages, key=ages.get))
Charlie
>>> print(min(ages, key=ages.get))
Lucy

感谢对不同问题的回答提供了这个用例!

这样做的目的是,如果没有找到键,您可以给出一个默认值,这非常有用

dictionary.get("Name",'harry')

在Python 3.8及以后版本中,字典get()方法可以与赋值表达式中的walrus操作符:=一起使用,以进一步减少代码:

if (name := dictonary.get("Name")) is not None
    return name

使用[]而不是get()将需要将代码包装在try/except块中并捕获KeyError(未显示)。如果没有walrus操作符,您将需要另一行代码:

name = dictionary.get("Name")
if (name is not None)
    return name