通过字典与非字符串关键字在kwargs发挥作用 [英] Pass dict with non string keywords to function in kwargs

查看:186
本文介绍了通过字典与非字符串关键字在kwargs发挥作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与有签名 F功能(* ARGS,** kwargs)库工作
我需要通过蟒蛇字典在kwargs的说法,但字典包含不关键字串

I work with library that has function with signature f(*args, **kwargs). I need to pass python dict in kwargs argument, but dict contains not strings in keywords

f(**{1: 2, 3: 4})
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: f() keywords must be strings

如何才能解决这个问题,而无需编辑功能?

How can I get around this without editing the function?

推荐答案

非字符串关键字参数仅仅是不允许的,所以这个问题没有通用的解决方案。您的具体的例子可以通过转换的关键是固定你的字典来的字符串:

Non-string keyword arguments are simply not allowed, so there is no general solution to this problem. Your specific example can be fixed by converting the keys of your dict to strings:

>>> kwargs = {1: 2, 3: 4}
>>> f(**{str(k): v for k, v in kwargs.items()})

这篇关于通过字典与非字符串关键字在kwargs发挥作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆