代码之家  ›  专栏  ›  技术社区  ›  Juicy

复制和格式化子dict

  •  0
  • Juicy  · 技术社区  · 6 年前

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

    这是一个自我包含的最低限度的例子,我正在努力实现:

    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 回复  |  直到 6 年前
        1
  •  2
  •   dyukha    6 年前

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

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