Format **kwargs to f-string

Viewed 865

I am trying to format keyword arguments passed to a function, in such a way that the string output (has to be f-string in this case) would look like arg1=arg1_value, arg2=arg2_value,...

Apparently it is not possible to just do:

out = f'{**kwargs}'

so I have managed to do it in this way:

def to_string(**kwargs):
    return ', '.join([f'{k}={v}' for k,v in kwargs.items()])

> to_string(a=1, b=2)
'a=1, b=2'

Is there a way to do this more simply?

1 Answers

You can unpack an iterable (cf [another question]) but not a dictionnary.
Because you want the exact same output as f"{a=}, {b=}, {c=}" you will not find a solution much shorter than what you already have.

Related