Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to apply format to all strings in dictionary without f-strings

I have a dictionary that looks like this:

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

What's the pythonic way of running format on all values in the dictionary? For example with x = 'TEST' the end result should be:

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

NB: I'm loading d from another module so can not use f-strings.

like image 930
Jimmy Sanchez Avatar asked Mar 02 '18 00:03

Jimmy Sanchez


People also ask

How do you use %d and %f in Python?

The %d formatter is used to input decimal values, or whole numbers. If you provide a float value, it will convert it to a whole number, by truncating the values after the decimal point. The %f formatter is used to input float values, or numbers with values after the decimal place.

How do you use %d strings in Python?

The %d operator is used as a placeholder to specify integer values, decimals or numbers. It allows us to print numbers within strings or other values. The %d operator is put where the integer is to be specified. Floating-point numbers are converted automatically to decimal values.

Are F-strings Pythonic?

When you're formatting strings in Python, you're probably used to using the format() method. But in Python 3.6 and later, you can use f-Strings instead. f-Strings, also called formatted string literals, have a more succinct syntax and can be super helpful in string formatting.


1 Answers

If you're using Python-3.6+ the pythonic way is using f-strings, otherwise a dictionary comprehension:

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()}
like image 151
Mazdak Avatar answered Nov 05 '22 19:11

Mazdak