python - 传递带有非字符串关键字的字典以在 kwargs 中运行

标签 python function python-3.x arguments

我使用的库具有签名 f(*args, **kwargs) 的功能。 我需要在 kwargs 参数中传递 python dict,但 dict 不包含关键字中的字符串

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

如何在不编辑函数的情况下解决这个问题?

最佳答案

非字符串关键字参数是不允许的,所以这个问题没有通用的解决方案。您的具体示例可以通过将 dict 的键转换为字符串来修复:

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

关于python - 传递带有非字符串关键字的字典以在 kwargs 中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14981810/

相关文章:

python - 从嵌套子列表返回八元组模式

python - tensorflow 从列表中收集相似的值

R函数不循环遍历列但重复第一行结果

c - 为什么 C 中的绝对值函数不接受 const 输入?

python - 如何在pycharm中安装pandas

python - ggplot geom_bar 正在绘制计数而不是值,即使启用了 stat ="identity"设置

python - 在哪里可以找到 Flask SQLAlchemy 列类型和选项的列表?

python - Ginput 为 datetimeindex 提供了错误的日期

python - python中的n-gram,四,五,六克?

c++ - 以随机顺序打印整数数组而不在C++中重复