Search code examples
pythondictionarykeyword-argument

Renaming **kwargs to pass in to another method


I've got the following methods. I was trying to pass in a number of variables to the first method and then rename them before passing them in to the second method.

def method2(**kwargs):
    # Print kwargs
    for key in kwargs:
        print(key, kwargs[key])

def method1(**kwargs):
    # Need to rename kwargs to pass in to method2 below
    # Keys are method1 kwargs variables and values are method 2 kwargs variables

    rename_dict = {'Val1': 'val_1', 'Val2': 'val_2', 'Val3': 'val_3'}
    new_kwargs = {}

    # The kwargs passed in method 1 need to their values to be set to the 
    # corresponding variables in the rename_dict before they are pass in method 2

    method2(**new_kwargs)

method1(Val1 = 5, Val2 = 6)

# Output desired
val_1 5
val_2 6

Solution

  • You could write it more concisely with a dict comprehension:

    new_kwargs = {rename_dict[key]: value for key, value in kwargs.items()}