使用格式化方法解压缩 Kwargs 的键冲突



我想用解包kwargs通过格式方法打印字符串。 但是,对于需要与一个字典映射的性别输入。 我能找到的唯一方法是创建一个字典并使用不同的键。 但这似乎不是一个好方法。 有吗?

def func(**kwargs):
    _m = {'h': 'he', 's': 'she'}
    print('This is {name}. {gender} is a {position}'.format(gender=_m[kwargs['sex']], **kwargs))

#correct
func(name='Jon', sex='h', position='Engineer')
#correct
func(name='Jon', sex='s', position='Engineer')
#incorrect
func(name='Jon', gender='s', position='Engineer')

首先,如果您在上一个示例中使用代码,则会得到KeyError,因为您没有传递尝试从内部_m字典中检索的sex参数。

仅使用所需的任何本地数据更新kwargs字典并仅使用 gender 属性并没有错,例如:

def func(**kwargs):
    _m = {'h': 'he', 's': 'she'}
    kwargs["gender"] = _m[kwargs["gender"]]
    print('This is {name}. {gender} is a {position}'.format(**kwargs))

您还可以通过创建字典映射来更新多个字段:

def func(**kwargs):
    replacements = {"gender": {"h": "he", "s": "she"}}
    for field in replacements:
        kwargs[field] = replacements[field].get(kwargs.get(field, None), None)
    print('This is {name}. {gender} is a {position}'.format(**kwargs))

然后,您可以使用任意数量的字段填充replacements字典,以便根据传递的参数进行预处理替换。

您甚至可以在默认值未传递时声明默认值,例如,如果您的replacements字典设置为:

replacements = {"gender": {"h": "he", "s": "she", None: "it"}}

缺少gender属性的调用将导致:

func(name='Robot', position='Engineer')
# This is Robot. it is a Engineer

最新更新