You need to enable JavaScript to run this app. 如何在Python嵌套字典中插入变量替换指定字段的值
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python嵌套字典中插入变量替换指定字段的值

问题解决方法

你使用.format()方法失败的核心原因:你需要修改的查询字符串是GraphQL语法,本身包含大量{}符号,.format()会默认把这些原生大括号识别为占位符处理,直接调用就会触发解析错误。

最优修改方案(对非Python开发者门槛最低)

使用Python的%格式化方法,不需要改动原有查询的其他结构,仅需两步操作:

  • 把查询字符串里的12345替换为占位符%s
  • 在查询字符串的闭合引号后添加 % account_id完成变量传入

修改后的完整可运行代码如下:

import requests

stacks = [{ "Key": "acc_1", "Value": "11111" },{ "Key": "acc_2", "Value": "22222"}]

for stack in stacks:
    account_id = stack['Value']
    account_name = stack['Key']
    data = {"query":"{\n  actor {\n    account(id: %s ) {\n      nrql(query: \"SELECT count(*) from Log where logtype = 'alb' AND elb_status_code = '502' OR elb_status_code = '504' AND target_processing_time = -1 AND response_processing_time = -1 FACET  elb_status_code, request since 12 hours ago\", timeout: 500) {\n        results\n      }\n    }\n  }\n}\n" % account_id, "variables":""}

如果你的account_id是字符串类型需要加引号,把占位符改成'%s'即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 13:24:04