Search code examples
pythonpython-3.xdictionarykeyword-argument

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, value in kwargs.items()), ">")

kwargs = {'foo__':'bar', 'foo_bar':'baz'}
some_func(name='some_name', kwargs)

# Output should be:
<some_name foo=bar foo-bar=baz >
#

So each key in kwargs needs to be replaced by:

{'foo':'bar', 'foo-bar':'baz'}

Which is essentially key.replace('__', '') and key.replace('_', '-').
I've tried using dictionaries for this:

key_to_replace = {'__':'', '_', '-'}

print(f"<{name}", *(f"{key.replace(key, value for key, value in key_to_replace.items())}={value}" for key, value in kwargs.items()), ">")

But it doesn't work, it says Generator Expression must be parenthesized
I've tried parenthesizing key, value for key, value in key_to_replace.items(), but it gives out SyntaxError.

How do I do this?


Solution

  • 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 >