【问题标题】:Copying and formating a child dict复制和格式化子字典
【发布时间】:2018-12-01 23:38:19
【问题描述】:

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

这是我正在努力实现的一个独立的极简主义示例:

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() 但这给了我相同的结果。

【问题讨论】:

    标签: python-3.x dictionary copy


    【解决方案1】:

    这是因为issue['detail'].format(domain=domain) 返回新字符串。你得到这个字符串,然后什么也不做。 如果要更改键的值,则应使用

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-17
      • 2019-08-05
      • 2016-12-06
      • 2011-02-14
      • 2019-10-14
      • 1970-01-01
      • 1970-01-01
      • 2011-08-09
      相关资源
      最近更新 更多