Skip to content Skip to sidebar Skip to footer

How Do I Replace Specific Substrings In Kwargs Keys?

I need to replace specific substrings in the key values of a dictionary. So: def some_func(name, **kwargs): ## Do stuff ## print(f'<{name}', *(f'{key}={value}' for key,

Solution 1:

Try:

def some_func(name, **kwargs):
    # replace the __ and _ accordingly:
    kwargs = {
        k.replace("__", "").replace("_", "-"): v for k, v in kwargs.items()
    }
    print(f"<{name}", *(f"{key}={value}" for key, value in kwargs.items()), ">")


kwargs = {"foo__": "bar", "foo_bar": "baz"}
some_func(name="some_name", **kwargs)    # <-- put ** here

Prints:

<some_name foo=bar foo-bar=baz >

Post a Comment for "How Do I Replace Specific Substrings In Kwargs Keys?"