【问题标题】:How do I properly format this API call?如何正确格式化此 API 调用?
【发布时间】:2018-08-25 18:20:21
【问题描述】:

我正在制作一个电报聊天机器人,但不知道如何从输出中取出 [{'

def tether(bot, update):
    tetherCall = "https://api.omniexplorer.info/v1/property/31"
    tetherCallJson = requests.get(tetherCall).json()
    tetherOut = tetherCallJson ['issuances'][:1]
    update.message.reply_text("Last printed tether:  " + str (tetherOut)+" Please take TXID and past it in this block explorer to see more info: https://www.omniexplorer.info/search")

我的用户会将此视为回复:[{'grant': '25000000.00000000', 'txid': 'f307bdf50d90c92278265cd92819c787070d6652ae3c8af46fa6a96278589b03'}]

【问题讨论】:

    标签: python json telegram-bot python-telegram-bot


    【解决方案1】:

    这看起来像一个包含单个字典的列表:

    [{'grant': '25000000.00000000',
      'txid': 'f307bdf50d90c92278265cd92819c787070d6652ae3c8af46fa6a96278589b03'}]
    

    您应该能够通过使用[0] 索引列表来访问字典...

    tetherOut[0]
    # {'grant': '25000000.00000000',
    #  'txid': 'f307bdf50d90c92278265cd92819c787070d6652ae3c8af46fa6a96278589b03'}
    

    ...如果你想从 dict 中获取一个特定的值,你可以通过它的名字来索引,例如

    tetherOut[0]['txid']
    # 'f307bdf50d90c92278265cd92819c787070d6652ae3c8af46fa6a96278589b03'
    

    不过,请小心链接这些东西。如果tetherOut 是一个空列表,tetherOut[0] 将生成一个IndexError。您可能想抓住它(以及无效的 dict 键将生成的 KeyError)。

    【讨论】:

    • 谢谢!有没有更快的方法来格式化 {} 或者我应该定义授权和 txid 并在同一行打印两者?
    • @toBePythonNinja,我不明白你的问题。 “更快地格式化{}”是什么意思?
    • 我想把它从字典 {} 中取出,然后打印:txid: f307bdf50d90c92278265cd92819c787070d6652ae3c8af46fa6a96278589b03
    • @toBePythonNinja,没有内置方法可以在字典之外同时打印键和值。但是您可以在字符串中包含文字 txid: ,例如'Last printed tether: txid: '.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-10
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 2014-09-22
    • 1970-01-01
    相关资源
    最近更新 更多