Home > Article > Backend Development > The difference between python dict.get() and dict['key']
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['age'] KeyError: 'age' In [4]: a.get('age', 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('age')) 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!