While Using Python Dictionary DataStructure (which contains key-value pair) if i want to retrieve some value from my Dictionary i have two options d[”] and g.get(‘key’) so i am confused now which is better and Why ?? I understand both some way but when it comes to memory consumption and evaluation in memory which one is better ??
Hoping for some Positive reply,
Regards.
From the Python Library Docs
and
The difference lies in the return value. When you ask for the value corresponding to a non-existing key, you either want
KeyErrorraisedPython provides the different functionalities through multiple methods.
There will be a performance hit using
[]when the key is not found, either in calling_missing_or raising the exception. As to which one is faster when the key IS present, I checked the source code. (I used 2.7.2 for this check.) Indictobject.cwe see:getcallsdict_get[]callsdict_subscriptNow if the values are present, in
dict_getwe haveand in
dict_subscriptwe haveThe only difference is that
getdoes an extra unpack tuple!Significant? I have no idea. 🙂