【问题标题】:String replace/format placeholder values in a nested python dictionary嵌套python字典中的字符串替换/格式化占位符值
【发布时间】: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


【解决方案1】:

你可以有另一个 dict 和你的变量和一个递归替换它们在字符串值中的函数

def replace_in_dict(input, variables):
    result = {}
    for key, value in input.iteritems():
        if isinstance(value, dict):
            result[key] = replace_in_dict(value, variables)
        else:
            result[key] = value % variables
    return result


example_dict = {
    'key_one': '%(replace_this)s',
    'key_two': '%(also_replace_this)s lorem ipsum dolor',
    'key_three': {
        'nested_key_one': '%(and_this)s',
        'nested_key_two': '%(replace_this)s',
    },
}

variables = {
    "replace_this": "my first value",
    "also_replace_this": "this is another value",
    "and_this": "also this",
    "this_is_not_replaced": "im not here"
}

print replace_in_dict(example_dict, variables)
# returns {'key_two': 'this is another value lorem ipsum dolor',
#'key_one': 'my first value',
# 'key_three': {'nested_key_two': 'my first value', 'nested_key_one': 'also this'}}

【讨论】:

    猜你喜欢
    • 2017-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-13
    • 2021-04-21
    • 1970-01-01
    • 2012-07-26
    • 2019-09-06
    相关资源
    最近更新 更多