You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何正确判断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 the payload dictionary has a "token" key. The in operator checks if the specified key exists in the dict, regardless of its value.
  • I fixed the timedout condition: In your original dictionary, 'type' is a top-level key (not nested inside payload), so message['type'] is the correct way to access it—your original code would have thrown a KeyError here.
  • For the locked check, I assumed you want to verify if "locked" is a key in payload (following the same pattern as the token check). Adjust this if your actual use case differs.

内容的提问来源于stack exchange,提问作者Arya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:14:34