使用非字符串关键字传递 dict 以在 kwargs 中运行 [英] Pass dict with non string keywords to function in kwargs

查看:14
本文介绍了使用非字符串关键字传递 dict 以在 kwargs 中运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

f(**{1: 2, 3: 4})回溯(最近一次调用最后一次):文件<console>",第 1 行,在 <module> 中类型错误:f() 关键字必须是字符串

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

解决方案

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

<预><代码>>>>夸格 = {1: 2, 3: 4}>>>f(**{str(k): v for k, v in kwargs.items()})

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()})

这篇关于使用非字符串关键字传递 dict 以在 kwargs 中运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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