首页 文章

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

提问于
浏览
420

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

这个功能用于什么目的?如果我想找到与字典中的键相关联的值,我可以执行 dict[key] ,它返回相同的内容:

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

9 回答

  • 697

    什么是dict.get()方法?

    如前所述, get 方法包含一个指示缺失值的附加参数 . From the documentation

    get(key [,default])
    如果key在字典中,则返回key的值,否则返回default . 如果未给出default,则默认为None,因此此方法永远不会引发KeyError .

    一个例子可以是

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

    在任何地方都有速度提升吗?

    如上所述here

    现在看来,所有三种方法都表现出相似的性能(彼此相差约10%),或多或少独立于单词列表的属性 .

    早些时候 get 相当慢,但现在速度几乎可以与返回默认值的额外优势相比 . 但要清除所有查询,我们可以在相当大的列表上进行测试(请注意,测试包括仅查找所有有效键)

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

    现在使用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
    

    我们可以看到查找比get更快,因为没有函数查找 . 这可以通过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
    

    哪里有用?

    每当您想要在查找字典时提供默认值时,它将非常有用 . 这减少了

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

    到一行, val = dic.get(key,def_val)

    它在哪里没用?

    每当您想要返回 KeyError ,表明特定密钥不可用时 . 返回默认值也会带来特定默认值也可能是关键的风险!

    是否有可能在dict ['key']中获得相似的功能?

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

    一个示例程序可以

    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'
    
  • 17

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

    同样,如果您尝试从列表中捕获单个值,我会使用'.join(列表)而不是列表[0] .

    希望能帮助到你 .

    [编辑]这是一个实际的例子:

    比如说,您正在调用API,它返回您需要解析的JOSN文件 . 第一个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"}}
    

    第二个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”键,这在任何数据结构中都很正常 .

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

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

    您可以,但它会为第二个JSON行提供回溯错误,因为该键根本不存在 .

    对此进行编码的适当方式可能如下:

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

    {'x':None}可以避免第二级出错 . 当然,如果你正在进行抓取,你可以在代码中 Build 更多的容错能力 . 就像首先指定if条件一样

  • 14

    这个功能的用途是什么?

    一个特殊的用法是用字典计数 . 假设您想要计算给定列表中每个元素的出现次数 . 这样做的常用方法是创建一个字典,其中键是元素,值是出现次数 .

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

    目的是如果找不到密钥,您可以给出默认值,这非常有用

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

    get 采用第二个可选值 . 如果字典中不存在指定的键,则返回此值 .

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

    如果您不提供第二个参数,将返回 None .

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

  • 26

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

    0.摘要

    dict[key] 相比, dict.get 在查找密钥时提供了回退值 .

    1.定义

    get(key [,default])4. Built-in Types — Python 3.6.4rc1 documentation

    如果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.问题解决了 .

    如果没有 default value ,则必须编写繁琐的代码来处理此类异常 .

    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 有一个额外的默认值选项来处理异常,如果字典中没有键

  • 0

    如果缺少密钥,它允许您提供默认值:

    dictionary.get("bogus", default_value)
    

    返回 default_value (无论你选择它是什么),而

    dictionary["bogus"]
    

    会举起一个 KeyError .

    如果省略, default_valueNone ,这样

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

    返回 None 就像

    dictionary.get("bogus", None)
    

    将 .

  • 0

    根据用法应使用此 get 方法 .

    Example1

    In [14]: user_dict = {'type': False}
    
    In [15]: user_dict.get('type', '')
    
    Out[15]: False
    
    In [16]: user_dict.get('type') or ''
    
    Out[16]: ''
    

    Example2

    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'
    
  • 0

    如果该键不存在,

    • dict.get 将默认不返回任何内容,但如果您放入它的第二个参数,则如果该键不存在则返回该值 .

    如果密钥不存在,

    • OTOH dict[key] 将引发 KeyError .

    这是一个例子(阅读评论):

    >>> d={'a':[1,2,3],'b':[4,5,6]} # Create a dictionary
    >>> d['c'] # Hoops, error key does not exist
    Traceback (most recent call last):
      File "<pyshell#7>", line 1, in <module>
        d['c']
    KeyError: 'c'
    >>> d.get('c') # no error because of `get`, so nothing returned
    >>> print(d.get('c')) # i print it, oh `None` is the output
    None
    >>> d.get('c',100) # Okay now i set second argument's value to `100`, hoopa output is `100`
    100
    >>> d['a'] # Works, key exist
    [1, 2, 3]
    >>> d.get('a') # work too, key exist
    [1, 2, 3]
    

相关问题