What is the main difference between:
>>> dic = {}
>>> existe = dic['key'] if 'key' in dic else None
>>> existe
None
Y:
>>> dic = {}
>>> existe = dic.get('key', None)
>>> existe
None
What is the most recommended for checking keys in a dictionary?
Or is it just a preference issue?
Regarding the result with both methods you get the same thing, in this case return the value of a key if it exists in the dictionary or
None
if it does not exist .Keep in mind that if we just want to check whether or not the dictionary contains a certain key (and we don't need to get the value associated with it), the simplest and most efficient way is to use the membership operator directly:
Where
existe
will be a boolean (True
/False
). In this case, it is checked if the key exists in the hash table (__contains__
), but its value is not obtained (__getitem__
).Returning to the
get
conditional vs, as to which is preferable, although it may be somewhat relative to what is "pythonic" to usedict.get
, it is readable, very compact and with the current C implementation of the method, the overhead is low. There are cases in which it is very helpful, for example when we search for values in nested dictionaries, very typical when working with JSON:dict.get
There is a case in which we could consider using the construction
if-else
(or ternary operator as in this case) for efficiency, this is when we know in advance that the vast majority of checks will lead to the return of the default value. In this specific case, in which the key does not exist, the overload causedget
by the function call makes it lose against the conditional, since in this case everything is reduced to a membership check using the operatorin
, a small example for measure the execution time of both methods (Python 3.6):It can be seen how
dict.get
it is practically insensitive to the existence or not of the key in the dictionary.You must bear in mind that a dictionary is a very fast and simple way of collecting data, so in a dictionary to know the keys , the len or any other function will be of a time O(1) that is to say constant temporality, so this is much faster than a list whose complexity is O(n) , in this case we have:
First, as I mentioned above, all the functions of a dictionary are of O(1) complexity, but this only occurs in the get function, but not if you put in , why? Simply because this is not a function of the dictionaries , get and others. functions have a peculiar way of working internally with a list (a bit complex but fast), so what happens with a in dic ?, we can associate this as a for i in dic but this is not a function of python dictionaries and being a cycle then it simply goes through absolutely the entire dictionary so this is of complexity O(n)(linear) which means to me that it goes through all the elements (just like lists) until it finds the object it is looking for.