如何正确判断Python字典的payload中是否包含token字段?
Correct Way to Check for "token" in the payload
Your current code is comparing the entire payload dictionary directly to the string 'token'—which will never evaluate to true, since message['payload'] is a dictionary, not a string. To properly check if the payload dictionary contains the key "token", you need to use Python's in operator, which checks for the presence of a key in a dictionary.
Fixed Code
Here's the adjusted version of your code with the correct check:
if 'token' in message['payload']: print("GOT IT"); print(message) elif message['type'] == 'timedout': # Note: 'type' is a top-level key, not inside payload! print("TIMEDOUT!") elif 'locked' in message['payload']: # Assuming 'locked' is a key in payload print("LOCKED!") done.set()
Key Explanations:
'token' in message['payload']: This is the right way to verify that thepayloaddictionary has a"token"key. Theinoperator checks if the specified key exists in the dict, regardless of its value.- I fixed the
timedoutcondition: In your original dictionary,'type'is a top-level key (not nested insidepayload), somessage['type']is the correct way to access it—your original code would have thrown aKeyErrorhere. - For the
lockedcheck, I assumed you want to verify if"locked"is a key inpayload(following the same pattern as the token check). Adjust this if your actual use case differs.
内容的提问来源于stack exchange,提问作者Arya
相关产品推荐
相关产品推荐

