Python: use a dict with lambda functions when using .format() on a string

Viewed 306

The setting is: I have a dict (format_dict), and in that dict there are lambda functions. If I want to read from the dict normally, it does not work like this:

    dict = {
    'name_U':  (lambda: name.upper()),
    'name_L':  (lambda: name.lower()),
    'name_fL': (lambda: name[0])
    }
    name = 'John'
    print(dict['name_U'])

because it returns:

<function <lambda> at 0x00000000E1F45012>

But if I instead do print(dict['name_U']()), it works as intended (printing JOHN).

The problem comes when I want to use this dict to format a string. If it is like this:

    print('My name in uppercase is {name_U}. The first letter is {name_fL}.'.format(**dict))

it returns

My name in uppercase is <function <lambda> at 0x00000000E1F45012>. The first letter is <function <lambda> at 0x00000000E1F46123>.

(where I would want the output to be My name in uppercase is JOHN. The first letter is J.)

If i try what i did in the 'normal' case (...format(**dict()))), it returns an error, saying TypeError: 'dict' object is not callable. Is there any way to circumvent this?

On a side note: I can't use the dict as

    dict = {
    'name_U':  name.upper(),
    'name_L':  name.lower(),
    'name_fL': name[0]
    }

because then the values of the dict will be the same after the assignment, even if name changes value.

2 Answers
dct = {
'name_U':  (lambda: name.upper()),
'name_L':  (lambda: name.lower()),
'name_fL': (lambda: name[0])
}

name = 'John'

print('my name in uppercase is {name_U}. The first letter is {name_fL}.'.format(**{k: v() for k, v in dct.items()}))

Prints:

my name in uppercase is JOHN. The first letter is J.

Or use f-strings, like in comments.

Use f-strings.

In [57]: dict = {
    ...: 'name_U':  (lambda: name.upper()),
    ...: 'name_L':  (lambda: name.lower()),
    ...: 'name_fL': (lambda: name[0])
    ...: }

In [58]:

In [58]: print(f'my name in uppercase is {dict["name_U"]()}. The first letter is {dict["name_fL"]()}')
my name in uppercase is JOHN. The first letter is J
Related