checking if a key exists in a dictionary
Python dictionaries use the operator in
to check whether a key exists or not - then a if
could turn out like this:
if not 'authenticated' in jsons or not jsons['authenticated']:
When we want to know if one thing nay is contained in another, as above, there is an alternative syntax that is recommended - write "not" along with "in" -
(I am explaining separately, why this is a syntax exception that compiles the code in a special way. Ordinarily the not
is an unary operator):
if not 'authenticated' in jsons or not jsons['authenticated']:
The style recommendations for writing Python programs indicate this form instead of the first.
Recommended form:
And finally, the recommended way - when you want to know at the same time if a key exists in a dictionary and if it exists, compare its value, the correct way is to use the method .get
dictionaries, instead of the two-stage expression as above. The .get
tries to find a value in the dictionary, and, if it does not exist, returns None
(instead of KeyError
):
if jsons.get("authenticated"):
# Código só é executado aqui se a chave `authenticated` existir
# e o seu valor for um objeto com valor verdadeiro.
Just to top it off, the method .get
accepts an optional second argument, which is the value returned if the key does not exist. Then you can write:
if jsons.get("authenticated", False):
It is more clear that if the value does not exist, it is considered as if it were False
.
Just to top it off:
Besides the method .get
, Python dictionaries also have the method .setdefault
. It always accepts two arguments and works like the .get
: if the key exists in the dictionary, the value that exists is returned. If the key does not exist, the second argument is returned. The difference is that in this case, it not only returns the value, but calf the value in the dictionary also.
It is useful when we are, for example, creating a dictionary in which values will be lists - if we want for example to have a dictionary with all the positions of words in a list:
dados = ["urso", "gato", "cachorro", "cachorro", "urso", "gato", "gato", "gato"]
resultados = {}
for posicao, palavra in enumerate(dados):
resultados.setdefault(palavra, []).append(posicao)
That is, for each word, if it does not yet exist as a key in the dictionary, a new empty list is created and placed there. If the word already exists, the list already in the dictionary is returned. In any case, the .setdefault
returns a list, and we’re done append
in the list to include the desired value (in this case, the position of the word);
The way out of this will be:
In [163]: resultados
Out[163]: {'urso': [0, 4], 'gato': [1, 5, 6, 7], 'cachorro': [2, 3]}
Very good explanation, thanks, just a supplementary doubt, this json,get(value, param) can only be True or False?
– user148010
No - the second argument can be anything. There is also the method
.setdefault
- that if the value does not exist, it is created in the dictionary.– jsbueno