复制并格式化子字典

时间:2018-12-01 23:38:19

标签: python-3.x dictionary copy

我正在尝试使用词典词典来方便一些报告。字典包含一些带有格式变量的模板;我想填充这些。

这是我要实现的目标的独立示例:

ISSUES = {
    'BIG_ISSUE': {
        'code': 1,
        'title': 'Something interesting',
        'detail': 'This is the affected domain {domain}'
    },
    'OTHER_ISSUE': {
        'code': 2,
        'title': 'Some other issue',
        'detail': 'Blah.'
    }
}

domain = 'foo.bar'
issue = ISSUES['BIG_ISSUE']
issue['detail'].format(domain=domain)

print(issue)

这是上面的输出:

{'code': 1, 'title': 'Something interesting', 'detail': 'This is the affected domain {domain}'}

请注意,上面的{domain}未在输出中格式化。

这是我正在寻找的预期结果:

{'code': 1, 'title': 'Something interesting', 'detail': 'This is the affected domain foo.bar'}

我相信这是由于字符串是不可变的吗?我尝试遵循SO上的一些示例,并尝试使用dict()import copy; copy.deepcopy(),但这给了我相同的结果。

1 个答案:

答案 0 :(得分:2)

这是因为issue['detail'].format(domain=domain)返回了新字符串。您得到此字符串,然后对其不执行任何操作。 如果要更改键的值,则应使用

issue['detail'] = issue['detail'].format(domain=domain)