格式字符串中的python dict

格式字符串中的python dict,python,dictionary,string-formatting,Python,Dictionary,String Formatting,我想用字符串编写python词典。项目的值应通过格式化字符串给出 我希望下面的代码可以工作,但它没有工作,因为用于定义dict的第一个“{”被解释为格式化字段 In: "{'key_1': '{value}'}".format(**{'value': 'test'}) 以下操作正常,但不会返回预期的dict: In: "'key_1': '{value}'".format(**{'value': 'test'}) Out: "'key_1': 'test'" 克服此问题的一种方法是使用列表b

我想用字符串编写python词典。项目的值应通过格式化字符串给出

我希望下面的代码可以工作,但它没有工作,因为用于定义dict的第一个“{”被解释为格式化字段

In: "{'key_1': '{value}'}".format(**{'value': 'test'})
以下操作正常,但不会返回预期的dict:

In: "'key_1': '{value}'".format(**{'value': 'test'})
Out: "'key_1': 'test'"
克服此问题的一种方法是使用列表brakets,然后用dict brakets替换它们:

In: "['key_1': '{value}']".format(**{'value': 'test'}).replace('[', '{').replace(']', '}')
Out: "{'key_1': 'test'}"

如何以更好的方式编写此文档?

使用double
{{{
}

 "{{'key_1': '{value}'}}".format(**{'value': 'test'})

您应该看看Python的
json
模块。