简体   繁体   中英

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

You could write it more concisely with a dict comprehension:

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

In order to rename the dict keys, you can use the following:

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

In addition, you can iterate dictionary in python using items() which returns list of tuples (key,value) and you can unpack them directly in your loop:

def method2(**kwargs):
    # Print kwargs
    for key, value in kwargs.items():
        print(key, value)

I was able to do this by adding a for loop in the first 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 = {}
    for key in kwargs:
        new_kwargs[rename_dict[key]] = kwargs[key]
    print(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

{'val_1': 5, 'val_2': 6}
val_1 5
val_2 6

I didn't realize you could pass variable names as strings in a python method. I hope I'm able to help someone trying to do the same thing!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM