本文翻译自: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            112 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'

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

  1. 纠正存储 dict 的元素前是计算 key 的 hash 值?

    前几天发了一篇名为 存储 dict 的元素前是计算 key 的 hash 值? 的文章,因缺乏相关的背景知识,导致得出了不正确的推论. 那篇文章的推论是 在不考虑 hash 冲突的情况下, 'a' 所 ...

  2. python中iteritems,Python2中的dict.items()和dict.iteritems()有什么区别?

    Are there any applicable differences between dict.items() and dict.iteritems()? dict.items(): Return ...

  3. python dict hash_【python-dict】dict的使用及实现原理

    以下内容是针对:python源码剖析中的第五章--python中Dict对象 的读书笔记(针对书中讲到的内容进行了自己的整理,并且针对部分内容根据自己的需求进行了扩展) 一.Dict的用法 Dict的 ...

  4. dict后缀_基本数据类型(dict)

    基本数据类型(dict)字典(键值对) ​ 字典(dict)是python中唯⼀的⼀个映射类型.他是以{ }括起来的键值对组成. 在dict中key是 唯⼀的. 在保存的时候, 根据key来计算出⼀个 ...

  5. python dict遍历_python遍历字典dict的几种方法汇总

    python遍历字典dict的方法: dic={'a':'how','b':'are','c':'you'}; 方法1, for key in dic: print key,dic[key] 方法2, ...

  6. python的dict类型_python数据类型:dict(字典)

    一.字典的简单介绍 字典(dict)是python中唯一的一个映射类型.他是以{}括起来的键值对组成. 语法: {key1:value1,key2:value2......} 注意:key必须是不可变 ...

  7. dict.items()和dict.iteritems()有什么区别?

    本文翻译自:What is the difference between dict.items() and dict.iteritems()? Are there any applicable dif ...

  8. python 两个dict合并,Python 中两个字典(dict)合并_python dict 合并_python 两个dict合并...

    Python 中两个字典(dict)合并_python dict 合并_python 两个dict合并 dict1={1:[1,11,111],2:[2,22,222]} dict2={3:[3,33 ...

  9. Redis源码分析:过期key删除与设置key的过期时间

    Redis中设置key过期时间与过期key的处理流程 在Redis中,可以再设置值的时候就设置该Key的过期时间,也可以通过在expire命令来设置某个key值的过期时间,并且在了解完设置过期时间之后 ...

最新文章

  1. 在pycharm中安装第三方库
  2. zlib和openssl相关库错误的解决
  3. Linux 高性能服务器编程——socket选项
  4. 袁隆平等专家联袂直播 启动农民丰收节交易会消费季活动
  5. vi文本编辑器的使用
  6. JavaWeb学习总结(五十三)——Web应用中使用JavaMail发送邮件
  7. Flask框架后端开发常见错误处理(2018/11/14)
  8. Android源码中添加 修改应用
  9. ubuntu18.04设置开机自启动的脚本
  10. 3D MAX2014 安装教程(个人亲自示例)
  11. matlab主成分分析代码
  12. CAD高版本窗体阵列LISP_AutoCAD高版本把阵列对话框调出来
  13. 银行卡号码显示每隔4位数空一格
  14. SCI,SSCI,EI傻傻分不清
  15. 评联想收购IBM PC
  16. uc浏览器设置里面的的浏览器ua是什么意思
  17. 黑苹果open core引导 选择系统界面黑屏,但是可以盲操作左右移动和回车,进度条第一阶段没有苹果logo
  18. Android Snackbar基本使用
  19. 初中级前端程序员面试中小型公司会问哪些问题?
  20. xml的三种解析方式

热门文章

  1. Unity脚本在层级面板中的执行顺序测试3
  2. git 2015-5-26
  3. ASP.NET页面输出缓存知识
  4. How to Use File Choosers
  5. 在ListView中使用DropDownList绑定数据……好麻烦
  6. Nginx取消泛解析
  7. 关于jmeter 加载jar文件的疑问
  8. 【洛谷P3369】 (模板)普通平衡树
  9. 【Codevs3027】线段覆盖2
  10. thinkphp--多个id查询