0

I have the following Python dict. I'm trying to do a check with n if statement that payload contains "token"

{'payload': {'token': '3u4td7393493d9304'}, 'type': 'send'}

Below is the python code

if message['payload'] == 'token':
    print("GOT IT");
    print(message)
elif message['payload']['type'] == 'timedout':
    print("TIMEDOUT!")
elif message['payload'] == 'locked':
    print("LOCKED!")
    done.set()

The current if statement for token is wrong. What is the proper way of checking if payload has "token" inside it?

1
  • 1
    type isn't in the payload dict, it's in the message dict. Shouldn't it be message['type'] == 'timedout'? Commented Apr 6, 2018 at 0:55

3 Answers 3

2

To check whether a dictionary d contains key k, use k in d:

message = {'payload': {'token': '3u4td7393493d9304'}, 'type': 'send'}
        # {'payload': {'locked': 'lockId'}, 'type': 'send'}

if 'token' in message['payload']:
    print("GOT IT");
    print(message)
    print(f"token: {message['payload']['token']}")
elif message['type'] == 'timedout':
    print("TIMEDOUT!")
elif 'locked' in message['payload']:
    print("LOCKED!")
    print(f"locked value: {message['payload']['locked']}")
    # done.set()

Since you have nested dictionaries, message['payload'] is itself a dictionary, therefore to check whether it has key 'token', you have to use 'token' in message['payload'].

I've also added an example that demonstrates how to access the value that corresponds to the key 'token'.

Side note: this if-else does not seem to be exhaustive, and it lacks the default case. Maybe you should approach it a bit more systematically, and first make sure that you deal with every possible type of the message, and then for each type deal with each kind of payload.

Sign up to request clarification or add additional context in comments.

Comments

1

The way i understand your question is you want to find whether or not 'token' exist in payload, regardless of the token value?

If yes, simple in array would suffice:

dc = {'payload': {'token': '3u4td7393493d9304'}, 'type': 'send'}

'token' in dc['payload'] # this would result in True

Comments

0

Just create a function which return True or False , now whenever you want to check pass value to that function and check :

def check_token(data_):
    if 'token' in data_['payload']:
        return True
    else:
        return False

Now back to your code , you can simply check by passing value to this function :

if check_token(data)==True:
    print("GOT IT")

output:

GOT IT

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.