简体   繁体   English

Python字典-dict.get(key)和dict.get(key,{})之间的区别

[英]Python dictionaries - difference between dict.get(key) and dict.get(key, {})

When getting values from a dictionary, I have seen people use two methods: 从字典中获取值时,我已经看到人们使用两种方法:

dict.get(key)

dict.get(key, {})

They seem to do the same thing. 他们似乎做同样的事情。 What is the difference, and which is the more standard method? 有什么区别,哪种是更标准的方法?

Thank you in advance! 先感谢您!

The second parameter to dict.get is optional: it's what's returned if the key isn't found. dict.get的第二个参数是可选的:如果找不到密钥,则返回该参数。 If you don't supply it, it will return None . 如果您不提供,它将返回None

So: 所以:

>>> d = {'a':1, 'b':2}
>>> d.get('c')
None
>>> d.get('c', {})
{}

From the documentation : 文档中

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

The typical way to look things up in a dictionary is d[key] , which will raise KeyError when the key is not present. 在字典中查找内容的典型方法是d[key] ,如果不存在该键,则会引发KeyError

When you don't want to search for documentation, you can do: 当您不想搜索文档时,可以执行以下操作:

d = {}
help(d.get)

which will display the docstring for the the get method for dictionary d . 它将显示字典dget方法的文档字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM