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

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

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

当前回答

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

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)

会。

其他回答

Get接受第二个可选值。如果指定的键在您的字典中不存在,则将返回此值。

dictionary = {"Name": "Harry", "Age": 17}
dictionary.get('Year', 'No available data')
>> 'No available data'

如果不提供第二个参数,则返回None。

如果使用dictionary['Year']中的索引,则不存在键将引发KeyError。

这个函数的用途是什么?

一个特别的用法是用字典计数。让我们假设您想要计算给定列表中每个元素的出现次数。常见的方法是创建一个字典,其中键是元素,值是出现的次数。

fruits = ['apple', 'banana', 'peach', 'apple', 'pear']
d = {}
for fruit in fruits:
    if fruit not in d:
        d[fruit] = 0
    d[fruit] += 1

使用.get()方法,你可以使这段代码更紧凑和清晰:

for fruit in fruits:
    d[fruit] = d.get(fruit, 0) + 1

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

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

有一个区别,这可能是一个优势,如果我们正在寻找一个不存在的键,我们将得到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

为什么dict.get(key)而不是dict[key]?

0. 总结

与dict[键]相比,dict。Get在查找键时提供一个回退值。

1. 定义

Get (key[, default])内置类型- Python 3.6.4rc1文档

如果key在字典中,则返回key的值,否则为default。如果没有给出default,则默认为None,因此该方法永远不会引发KeyError。

d = {"Name": "Harry", "Age": 17}
In [4]: d['gender']
KeyError: 'gender'
In [5]: d.get('gender', 'Not specified, please add it')
Out[5]: 'Not specified, please add it'

2. 问题解决了。

如果没有默认值,则必须编写繁琐的代码来处理此类异常。

def get_harry_info(key):
    try:
        return "{}".format(d[key])
    except KeyError:
        return 'Not specified, please add it'
In [9]: get_harry_info('Name')
Out[9]: 'Harry'
In [10]: get_harry_info('Gender')
Out[10]: 'Not specified, please add it'

作为一个方便的解决方案,dict。Get引入了一个可选的默认值,避免了上述杂乱的代码。

3.结论

字典Get有一个额外的默认值选项,用于在字典中缺少key时处理异常