Python isset check (details)

Asked

Viewed 171 times

3

My question is this, in PHP I have a code curl that returns some json as you can see in the code:

$response = curl_exec($request);

$header_size = curl_getinfo($request, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$json = substr($response, $header_size);
$json = json_decode($json);

curl_close($request);

Checks if the object exists authenticated, is here my problem in Python, as I see it in python?

if (isset($json->authenticated) && $json->authenticated === false && $json->user === true)
{
  return ['incorrect_password'];
}

In python I have the same thing, but I need to check this isset($json->authenticated)

Behold:

post = response['session'].post(self.url['login'], data=data, headers=headers, allow_redirects=False)

jsons = json.loads(post.text)

if not jsons['authenticated'] and not jsons['user']:
  return 'incorrect_user'

I’ve already tried:

if jsons['authenticated'] and not jsons['authenticated'] and not jsons['user']:

I even tried the use of try | exceptions

But I don’t understand that logic.

How to do it properly?

1 answer

2


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?

  • 1

    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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.