【发布时间】:2016-01-07 21:47:11
【问题描述】:
假设我有一个这样的嵌套字典:
example_dict = {
'key_one': '{replace_this}',
'key_two': '{also_replace_this} lorem ipsum dolor',
'key_three': {
'nested_key_one': '{and_this}',
'nested_key_two': '{replace_this}',
},
}
格式化占位符字符串值并返回新字典或编辑现有example_dict 的最佳方法是什么?另外,考虑任何深度。
更新
我尝试了其他方法。
import json
output = json.dumps(example_dict)
output = output.format(replace_this='hello')
虽然我在 .format() 语句中遇到的第一个键上出现 KeyError。
【问题讨论】:
-
您要替换
{和}之间的任何内容。或者是否有一组非常具体的字符串要替换?
标签: python dictionary replace format placeholder