Home  >  Article  >  Backend Development  >  The difference between python dict.get() and dict['key']

The difference between python dict.get() and dict['key']

高洛峰
高洛峰Original
2017-03-01 13:58:431838browse

Look at the code first:

In [1]: a = {'name': 'wang'} 
 
In [2]: a.get('age') 
 
In [3]: a['age'] 
---------------------------------------------------------------------------
KeyError                 Traceback (most recent call last) 
<ipython-input-3-a620cb7b172a> in <module>() 
----> 1 a[&#39;age&#39;] 
 
KeyError: &#39;age&#39;
 
In [4]: a.get(&#39;age&#39;, 10) 
Out[4]: 10

So, dict['key'] can only get the existing value, if it does not exist, KeyError will be triggered

And dict.get(key, default=None) returns a default value if it does not exist, if it is set, it is set, otherwise it is None

In [6]: type(a.get(&#39;age&#39;)) 
Out[6]: NoneType

The above detailed explanation of the difference between python dict.get() and dict['key'] is all the content shared by the editor. I hope it can give you a reference, and I hope you can support me more. PHP Chinese website.

For more related articles on the difference between python dict.get() and dict['key'], please pay attention to the PHP Chinese website!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn