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

Python 为什么dict.get(key)而不是dict[key]?,python,dictionary,Python,Dictionary,今天,我遇到了dict方法get,它在字典中给定一个键,返回相关的值 此功能的用途是什么?如果我想在字典中找到与键相关联的值,我只需执行dict[key],它就会返回相同的结果: dictionary = {"Name": "Harry", "Age": 17} dictionary["Name"] dictionary.get("Name") 它允许您在缺少密钥时提供默认值: dictionary.get("bogus", default_value) 返回默认值(无论您选择它是什么),而

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

此功能的用途是什么?如果我想在字典中找到与键相关联的值,我只需执行
dict[key]
,它就会返回相同的结果:

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

它允许您在缺少密钥时提供默认值:

dictionary.get("bogus", default_value)
返回默认值(无论您选择它是什么),而

将引发一个
键错误

如果省略,
默认值
,因此

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

会的

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

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

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

dictionary = {"Name": "Harry", "Age": 17}
dictionary.get('Year', 'No available data')
>> 'No available data'
如果不提供第二个参数,将返回
None

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

如果像在
字典['Year']
中那样使用索引,不存在的键将引发
KeyError

我将给出一个使用python抓取web数据的实际示例,很多时候,您会得到没有值的键,在这种情况下,如果使用字典['key'],您将得到错误,而dictionary.get('key','return_otherly')没有问题

类似地,如果您试图从列表中捕获单个值,我将使用“”连接(列表)而不是列表[0]

希望能有帮助

[编辑]以下是一个实际示例:

比方说,您正在调用一个API,该API返回一个需要解析的JOSN文件

{"bids":{"id":16210506,"submitdate":"2011-10-16 15:53:25","submitdate_f":"10\/16\/2011 at 21:53 CEST","submitdate_f2":"p\u0159ed 2 lety","submitdate_ts":1318794805,"users_id":"2674360","project_id":"1250499"}}
for item in API_call:
    submitdate_ts = item["bids"]["submitdate_ts"]
for item in API_call:
    submitdate_ts = item.get("bids", {'x': None}).get("submitdate_ts")
第二个JOSN是这样的:

{"bids":{"id":16210506,"submitdate":"2011-10-16 15:53:25","submitdate_f":"10\/16\/2011 at 21:53 CEST","submitdate_f2":"p\u0159ed 2 lety","users_id":"2674360","project_id":"1250499"}}
请注意,第二个JSON缺少“submitdate_ts”键,这在任何数据结构中都很正常

因此,当您尝试在循环中访问该键的值时,可以使用以下命令调用它:

{"bids":{"id":16210506,"submitdate":"2011-10-16 15:53:25","submitdate_f":"10\/16\/2011 at 21:53 CEST","submitdate_f2":"p\u0159ed 2 lety","submitdate_ts":1318794805,"users_id":"2674360","project_id":"1250499"}}
for item in API_call:
    submitdate_ts = item["bids"]["submitdate_ts"]
for item in API_call:
    submitdate_ts = item.get("bids", {'x': None}).get("submitdate_ts")
可以,但它会为第二行JSON提供一个回溯错误,因为密钥根本不存在

对其进行编码的适当方式如下:

{"bids":{"id":16210506,"submitdate":"2011-10-16 15:53:25","submitdate_f":"10\/16\/2011 at 21:53 CEST","submitdate_f2":"p\u0159ed 2 lety","submitdate_ts":1318794805,"users_id":"2674360","project_id":"1250499"}}
for item in API_call:
    submitdate_ts = item["bids"]["submitdate_ts"]
for item in API_call:
    submitdate_ts = item.get("bids", {'x': None}).get("submitdate_ts")
{x':None}是为了避免第二级出错。当然,如果您正在执行刮取,您可以在代码中构建更多的容错性。就像首先指定if条件一样

什么是
dict.get()
方法?

如前所述,
get
方法包含一个额外的参数,用于指示缺少的值

如果key在dictionary中,则返回key的值,否则为default。如果未给出default,则默认为None,因此此方法不会引发
keyrerror

例如:

>>> d = {1:2,2:3}
>>> d[1]
2
>>> d.get(1)
2
>>> d.get(3)
>>> repr(d.get(3))
'None'
>>> d.get(3,1)
1
任何地方都有速度提升吗?

如前所述

这三种方法现在似乎表现出相似的性能(彼此相差不超过10%),或多或少与单词列表的属性无关

早期的
get
速度要慢得多,但是现在的速度几乎相当于返回默认值的额外优势。但是要清除所有查询,我们可以在相当大的列表上进行测试(注意,测试只包括查找所有有效键)

现在使用

正如我们所看到的,由于没有函数查找,查找速度比get快

它在哪里有用?

当您在查找字典时需要提供默认值时,它将非常有用

 if key in dic:
      val = dic[key]
 else:
      val = def_val
对于单行,
val=dic.get(键,定义值)

它在哪里没有用?

每当您想要返回一个
keyrerror
说明特定密钥不可用时。返回默认值也会带来特定默认值也可能是密钥的风险

是否可以在
dict['key']
中使用
get
类似功能?

是的!我们需要在dict子类中实现

可以使用一个示例程序

class MyDict(dict):
    def __missing__(self, key):
        return None
一个小的示范是可以的

>>> my_d = MyDict({1:2,2:3})
>>> my_d[1]
2
>>> my_d[3]
>>> repr(my_d[3])
'None'

根据使用情况,应使用此
get
方法

示例1

In [14]: user_dict = {'type': False}

In [15]: user_dict.get('type', '')

Out[15]: False

In [16]: user_dict.get('type') or ''

Out[16]: ''
示例2

In [17]: user_dict = {'type': "lead"}

In [18]: user_dict.get('type') or ''

Out[18]: 'lead'

In [19]: user_dict.get('type', '')

Out[19]: 'lead'
此功能的用途是什么

一种特殊用法是使用字典计数。假设您要计算给定列表中每个元素的出现次数。通常的方法是制作一个字典,其中键是元素,值是出现次数

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
为什么dict.get(key)而不是dict[key]

0.摘要 与
dict[key]
相比,
dict.get
在查找密钥时提供了一个回退值

1.定义 获取(键[,默认])

如果key在dictionary中,则返回key的值,否则为default。如果未给出default,则默认为None,因此此方法不会引发keyrerror

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.结论
dict.get
有一个额外的默认值选项,用于在字典中缺少键时处理异常

使用
.get()
时需要注意的问题:

如果字典包含调用
.get()
时使用的键,且其值为
None
,则
.get()
方法将返回
None
,即使提供了默认值

例如,以下返回的是
None
,而不是
“alt\u值”
,这可能是预期的:

d = {'key': None}
assert None is d.get('key', 'alt_value')
.get()
的第二个值仅在提供的键不在字典中时返回,而在返回值为
score = None
try:
    score = dictionary["score"]
except KeyError:
    score = 0
score = dictionary.get("score", 0)
# score = 0
>>> 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