Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在dict中插入变量作为值_Python_Json_String_Dictionary - Fatal编程技术网

Python 如何在dict中插入变量作为值

Python 如何在dict中插入变量作为值,python,json,string,dictionary,Python,Json,String,Dictionary,我正试图生成一个json有效负载来发布到API,但我很难让它正常工作 这就是我现在拥有的 def payload(user, macro_hostname, macro_servicedesc, macro_servicestate, macro_serviceoutput,nagios_url): payload = { 'username': '%s', 'text': '--- \n HOST: %s \n SERVICE: %s \n STATE: %s \n MESSAGE %

我正试图生成一个json有效负载来发布到API,但我很难让它正常工作

这就是我现在拥有的

def payload(user, macro_hostname, macro_servicedesc, macro_servicestate, macro_serviceoutput,nagios_url):
    payload = { 'username': '%s', 'text': '--- \n HOST: %s \n SERVICE: %s \n STATE: %s \n MESSAGE %s \n %s|see nagios for more information \n\n --- ' % user, macro_hostname, macro_servicedesc, macro_servicestate, macro_serviceoutput, nagios_url }
    return payload

除了它丑陋而且不太像蟒蛇,它还有一个明显的特点就是根本不起作用。我尝试过不同的方法,但我似乎一直在努力使它起作用;不幸的是,我真的没有找到一种方法来让它发挥作用


我知道str.format()比%s方法更受欢迎,但我很确定有一种完全不同的方法来做我想做的事情,这比我现在尝试做的事情要好得多。

如果我理解正确,您在初始化字符串时犯了一个错误,因为字符串格式化时出现了发音-->错误 将
用户
变量移动到词汇表中第一项旁边,并在最后一个变量中添加括号

def payload(user, macro_hostname, macro_servicedesc, macro_servicestate, macro_serviceoutput,nagios_url):
    payload = { 'username': '%s' %user, 
            'text': '--- \n HOST: %s \n SERVICE: %s \n STATE: %s \n MESSAGE %s \n %s|see nagios for more information \n\n --- ' % (macro_hostname, macro_servicedesc, macro_servicestate, macro_serviceoutput, nagios_url) }
    return payload

“它还有一个明显的特点,就是根本不工作。”-你能告诉我们出了什么问题吗?基本上出了问题的是,我可能对字符串格式了解不够,无法真正调试我的问题。阿尼尔的回答对我很有吸引力;我真的应该找一个更好的方法来最终做到这一点;但至少它现在起作用了。另一个发表评论的家伙有一个有效的解决方案;但是你的也很好用,而且看起来更漂亮。谢谢实际上,我更喜欢他的代码,我只是用这种方式编写它,以便与您编写的代码保持一致,这样您就可以与您的代码进行比较并进行修复。下一次:写下你的错误。