格式化字符串中的python dict

时间:2015-05-22 10:57:27

标签: python dictionary string-formatting

我想在字符串中写一个python字典。项目的值应由格式化字符串给出。

我预计以下内容可以正常工作,但它并不是因为用于定义dict的第一个'{'被解释为格式化字段

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

以下工作正常,但不会返回预期的字典:

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

克服这个问题的一种方法是使用list brakets并稍后用dict brakets替换它们:

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

如何以更好的方式写这个?

1 个答案:

答案 0 :(得分:0)

使用双{{}}

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