如何在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
相关产品推荐
相关产品推荐

