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.
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.
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.
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.
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()}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With