Pythonic way to apply format to all lines in a dictionary without f-lines

I have a dictionary that looks like this:

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

What is the pythonic startup method formatfor all values ​​in a dictionary? For example, with the x = 'TEST'final result should be:

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

NB: I load dfrom another module, so I can not use f-lines.

+4
source share
2 answers

If you are using Python-3.6 +, the pythonic way uses f-lines, otherwise - understanding the dictionary:

In [147]: x = 'TEST'

In [148]: d = {
     ...:   'hello': f'world{x}',
     ...:   'foo': f'bar{x}'
     ...: }

In [149]: d
Out[149]: {'foo': 'barTEST', 'hello': 'worldTEST'}

In python <3.6:

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

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

In python 3.6, use the f lines and then run the for loop to apply the changes to each value in the dict using the format method.

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

    }

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

, :

 worldTEST
 barTEST
0

Source: https://habr.com/ru/post/1694329/


All Articles