【问题标题】:String format with optional dict key-value带有可选 dict 键值的字符串格式
【发布时间】:2013-12-16 10:24:37
【问题描述】:

有没有办法用 dict 格式化字符串,但可以选择没有键错误?

这很好用:

opening_line = '%(greetings)s  %(name)s !!!'
opening_line % {'greetings': 'hello', 'name': 'john'}

但是假设我不知道名字,我想格式化上面的行 仅适用于'greetings'。比如,

 opening_line % {'greetings': 'hello'}

输出会很好,即使:

'hii %(name)s !!!'  # keeping name un-formatted 

但这会在解包时给出KeyError

有什么办法吗?

【问题讨论】:

标签: python dictionary string-formatting missing-data


【解决方案1】:

使用defaultdict,这将允许您为字典中不存在的键指定默认值。例如:

>>> from collections import defaultdict
>>> d = defaultdict(lambda: 'UNKNOWN')
>>> d.update({'greetings': 'hello'})
>>> '%(greetings)s  %(name)s !!!' % d
'hello  UNKNOWN !!!'
>>> 

【讨论】:

    【解决方案2】:

    defaultDict 的一些替代品,

    greeting_dict = {'greetings': 'hello'}
    
    if 'name' in greeting_dict :
        opening_line = '{greetings} {name}'.format(**greeting_dict)
    else:
        opening_line = '{greetings}'.format(**greeting_dict)
    
    print opening_line
    

    也许更简洁,使用字典 get 来设置每个参数的默认值,

    '{greetings} {name}'.format(greetings=greeting_dict.get('greetings','hi'),
                                name=greeting_dict.get('name',''))
    

    【讨论】:

    • 我会在if/else 中提取共性,而不是fmt = '{greetings} {name}' if 'name' in greeting_dict else '{greetings}'; print(fmt.format(**greeting_dict))
    【解决方案3】:

    记录在案:

    info = {
        'greetings':'DEFAULT',
        'name':'DEFAULT',
        }
    opening_line = '{greetings} {name} !!!'
    
    info['greetings'] = 'Hii'
    print opening_line.format(**info)
    # Hii DEFAULT !!!
    

    【讨论】:

      【解决方案4】:

      我遇到了和你一样的问题,并决定创建一个库来解决这个问题:pyformatting
      以下是您的 pyformatting 问题的解决方案:

      >>> from pyformatting import optional_format
      >>> opening_line = '{greetings}  {name} !!!'
      >>> optional_format(opening_line, greetings='hii')
      'hii  {name} !!!'
      

      唯一的问题是 pyformatting 不支持 python 2。pyformatting 支持 python 3.1+ 如果我看到任何关于需要 2.7 支持的反馈,我想我会添加该支持。

      【讨论】:

        【解决方案5】:

        您可以继承UserDict 并使用.format_map() 自定义__missing__

        from collections import UserDict
        
        
        class FormatMapper(UserDict):
            def __missing__(self, key):
                return f'{key=} is MISSING'
        
        
        info = FormatMapper({'greetings': 'hello', 'not_name': 'john'})
        opening_line = '{greetings}  {name} !!!'
        
        print(opening_line.format_map(info))
        

        输出:

        hello  key='name' is MISSING !!!
        

        【讨论】:

          猜你喜欢
          • 2014-01-07
          • 1970-01-01
          • 2013-04-22
          • 2022-01-16
          • 2019-01-24
          • 2015-11-13
          • 2019-04-13
          • 2018-09-05
          • 2012-02-12
          相关资源
          最近更新 更多