【问题标题】:Pythonic way to apply format to all strings in dictionary without f-strings将格式应用于字典中所有字符串的 Pythonic 方法,无需 f 字符串
【发布时间】:2018-08-10 04:28:49
【问题描述】:

我有一本像这样的字典:

d = {
  'hello': 'world{x}',
  'foo': 'bar{x}'
}

在字典中的所有值上运行format 的pythonic 方式是什么?例如x = 'TEST' 的最终结果应该是:

{
  'hello': 'worldTEST',
  'foo': 'barTEST'
}

注意:我正在从另一个模块加载 d,因此无法使用 f 字符串。

【问题讨论】:

    标签: python python-3.x dictionary formatting


    【解决方案1】:

    如果您使用的是 Python-3.6+,pythonic 方式是使用 f-strings,否则使用字典理解:

    In [147]: x = 'TEST'
    
    In [148]: d = {
         ...:   'hello': f'world{x}',
         ...:   'foo': f'bar{x}'
         ...: }
    
    In [149]: d
    Out[149]: {'foo': 'barTEST', 'hello': 'worldTEST'}
    

    在python

    d = {
         'hello': f'world{var}',
         'foo': f'bar{var}'
        }
    
    {k: val.format(var=x) for k, val in d.items()}
    

    【讨论】:

    • 我应该指定的,但是字典 d 在另一个模块中,使得 f-strings 方法不可能。我更新了我的问题和标题以反映这一点。
    • 在更一般的情况下(想使用范围内的任何变量),val.format(**globals()) 可能是合适的。
    • @PatrickHaugh:如果你想使用本地人,大概是locals()。您也可以使用format_map 代替format 来避免** 解包的需要。
    【解决方案2】:

    在 python 3.6 中使用 f 字符串,然后运行 ​​for 循环以使用 format 方法将更改应用于 dict 中的每个值。

    x = 'TEST'
    d = {
         'hello': f'world{x}',
          'foo': f'bar{x}'
    
        }
    
    for value in d.values():
         value.format(x)
         print(value)
    

    这将为您提供您正在寻找的输出:

     worldTEST
     barTEST
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-20
      • 2020-05-02
      • 2020-01-12
      • 2020-02-02
      相关资源
      最近更新 更多