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

本文翻译自:Why dict.get(key) instead of dict[key]?

Today, I came across the dict method get which, given a key in the dictionary, returns the associated value. 今天,我遇到了dict方法get ,在字典中给定键的情况下,该方法返回关联的值。

For what purpose is this function useful? 此功能用于什么目的? If I wanted to find a value associated with a key in a dictionary, I can just do dict[key] , and it returns the same thing: 如果我想找到与字典中的键相关联的值,则可以执行dict[key] ,并且它返回相同的内容:

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

#1楼

参考:https://stackoom.com/question/kKNB/为什么用dict-get-key-而不是dict-key


#2楼

It allows you to provide a default value if the key is missing: 如果密钥丢失,它允许您提供默认值:

dictionary.get("bogus", default_value)

returns default_value (whatever you choose it to be), whereas 返回default_value (无论您选择的是什么),而

dictionary["bogus"]

would raise a KeyError . 会引发KeyError

If omitted, default_value is None , such that 如果省略,则default_valueNone ,这样

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

returns None just like 返回None ,就像

dictionary.get("bogus", None)

would. 将。


#3楼

目的是如果找不到密钥,则可以提供默认值,这非常有用

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

#4楼

get takes a second optional value. get需要第二个可选值。 If the specified key does not exist in your dictionary, then this value will be returned. 如果字典中不存在指定的键,则将返回此值。

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

If you do not give the second parameter, None will be returned. 如果不提供第二个参数,则将返回None

If you use indexing as in dictionary['Year'] , nonexistent keys will raise KeyError . 如果像在dictionary['Year']那样使用索引,则不存在的键将引发KeyError


#5楼

I will give a practical example in scraping web data using python, a lot of the times you will get keys with no values, in those cases you will get errors if you use dictionary['key'], whereas dictionary.get('key', 'return_otherwise') has no problems. 我将举一个使用python抓取Web数据的实际示例,很多时候,您将获得没有值的键,在这些情况下,如果您使用dictionary ['key']会出错,而dictionary.get('key ','return_otherwise')没问题。

Similarly, I would use ''.join(list) as opposed to list[0] if you try to capture a single value from a list. 同样,如果您尝试从列表中捕获单个值,我将使用''.join(list)而不是list [0]。

hope it helps. 希望能帮助到你。

[Edit] Here is a practical example: [编辑]这是一个实际示例:

Say, you are calling an API, which returns a JOSN file you need to parse. 假设您正在调用一个API,该API返回您需要解析的JOSN文件。 The first JSON looks like following: 第一个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"}}

The second JOSN is like this: 第二个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"}}

Note that the second JSON is missing the "submitdate_ts" key, which is pretty normal in any data structure. 请注意,第二个JSON缺少“ submitdate_ts”键,这在任何数据结构中都是很正常的。

So when you try to access the value of that key in a loop, can you call it with the following: 因此,当您尝试循环访问该键的值时,可以使用以下命令调用它:

for item in API_call:
    submitdate_ts = item["bids"]["submitdate_ts"]

You could, but it will give you a traceback error for the second JSON line, because the key simply doesn't exist. 您可以,但是它将给您第二条JSON行的回溯错误,因为密钥根本不存在。

The appropriate way of coding this, could be the following: 适当的编码方式如下:

for item in API_call:
    submitdate_ts = item.get("bids", {'x': None}).get("submitdate_ts")

{'x': None} is there to avoid the second level getting an error. {'x':None}可以避免第二级出错。 Of course you can build in more fault tolerance into the code if you are doing scraping. 当然,如果您执行抓取操作,则可以在代码中内置更多的容错功能。 Like first specifying a if condition 就像首先指定一个if条件


#6楼

What is the dict.get() method? 什么是dict.get()方法?

As already mentioned the get method contains an additional parameter which indicates the missing value. 如前所述, get方法包含一个附加参数,该参数指示缺少的值。 From the documentation 从文档中

 get(key[, default]) 

Return the value for key if key is in the dictionary, else default. 如果key在字典中,则返回key的值,否则返回默认值。 If default is not given, it defaults to None, so that this method never raises a KeyError . 如果未提供default,则默认为None,因此此方法永远不会引发KeyError

An example can be 一个例子可以是

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

Are there speed improvements anywhere? 哪里有速度改进?

As mentioned here , 如前所述这里

It seems that all three approaches now exhibit similar performance (within about 10% of each other), more or less independent of the properties of the list of words. 似乎所有这三种方法现在都表现出相似的性能(彼此之间约占10%),或多或少地与单词列表的属性无关。

Earlier get was considerably slower, However now the speed is almost comparable along with the additional advantage of returning the default value. 早期的get速度要慢得多,但是现在速度几乎可以与返回默认值的其他优点相提并论。 But to clear all our queries, we can test on a fairly large list (Note that the test includes looking up all the valid keys only) 但是要清除所有查询,我们可以在相当大的列表上进行测试(请注意,该测试仅包括查找所有有效键)

def getway(d):
    for i in range(100):
        s = d.get(i)

def lookup(d):
    for i in range(100):
        s = d[i]

Now timing these two functions using timeit 现在使用timeit对这两个功能进行计时

>>> import timeit
>>> print(timeit.timeit("getway({i:i for i in range(100)})","from __main__ import getway"))
20.2124660015
>>> print(timeit.timeit("lookup({i:i for i in range(100)})","from __main__ import lookup"))
16.16223979

As we can see the lookup is faster than the get as there is no function lookup. 如我们所见,由于没有函数查找,查找比get快。 This can be seen through dis 通过dis可以看到

>>> def lookup(d,val):
...     return d[val]
... 
>>> def getway(d,val):
...     return d.get(val)
... 
>>> dis.dis(getway)
  2           0 LOAD_FAST                0 (d)
              3 LOAD_ATTR                0 (get)
              6 LOAD_FAST                1 (val)
              9 CALL_FUNCTION            1
             12 RETURN_VALUE        
>>> dis.dis(lookup)
  2           0 LOAD_FAST                0 (d)
              3 LOAD_FAST                1 (val)
              6 BINARY_SUBSCR       
              7 RETURN_VALUE  

Where will it be useful? 在哪里有用?

It will be useful whenever you want to provide a default value whenever you are looking up a dictionary. 每当您要查找字典时都想提供默认值时,它将很有用。 This reduces 这减少了

 if key in dic:
      val = dic[key]
 else:
      val = def_val

To a single line, val = dic.get(key,def_val) 对于单行, val = dic.get(key,def_val)

Where will it be NOT useful? 在哪里没有用?

Whenever you want to return a KeyError stating that the particular key is not available. 每当您想返回KeyError指出特定的键不可用时。 Returning a default value also carries the risk that a particular default value may be a key too! 返回默认值还会带来一个风险,即某个默认值也可能是键!

Is it possible to have get like feature in dict['key'] ? 是否有可能有get像功能dict['key']

Yes! 是! We need to implement the __missing__ in a dict subclass. 我们需要在dict子类中实现__missing__

A sample program can be 一个示例程序可以是

class MyDict(dict):
    def __missing__(self, key):
        return None

A small demonstration can be 一个小示范可以

>>> my_d = MyDict({1:2,2:3})
>>> my_d[1]
2
>>> my_d[3]
>>> repr(my_d[3])
'None'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值