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

高洛峰
Release: 2017-03-01 13:58:43
Original
1794 people have browsed it

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
Copy after login

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
Copy after login

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!


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!