Pythonic方式将格式应用于字典中的所有字符串而不使用f字符串

时间:2018-03-02 00:32:03

标签: python python-3.x dictionary formatting

我的字典看起来像这样:

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

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

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

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

2 个答案:

答案 0 :(得分:7)

如果您使用的是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< 3.6:

d = {
     'hello': f'world{var}',
     'foo': f'bar{var}'
    }

{k: val.format(var=x) for k, val in d.items()}

答案 1 :(得分:1)

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

Traceback (most recent call last):
        5: from t.rb:14:in `<main>'
        4: from t.rb:4:in `print_f'
        3: from t.rb:4:in `map'
        2: from t.rb:4:in `each'
        1: from t.rb:5:in `block in print_f'
t.rb:5:in `[]': no implicit conversion of String into Integer (TypeError)

这可以获得您正在寻找的输出:

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

    }

for value in d.values():
     value.format(x)
     print(value)