Python函数传入多个额外字典参数报参数数量错误如何解决
问题原因
你定义函数时使用的**kwargs是关键字参数收集器,仅能接收key=value形式传入的参数,无法匹配你传入的多个额外位置字典参数,才会触发参数数量不匹配的报错。你需要改为使用可变位置参数*args来收集所有额外传入的字典。
修改后的代码
def create_objection(name, position, *args): dicct = { 'name': name, 'position': position } print(len(args)) dicct.update({'extra_info': list(args)}) return dicct
调用效果验证
- 单字典参数调用
create_objection('c1',{'t':1}),输出如下:
0 {'name': 'c1', 'position': {'t': 1}, 'extra_info': []}
如果需要保持原有调用时extra_info为空字典的格式,只需修改赋值逻辑为:
dicct.update({'extra_info': dict() if not args else list(args)})
- 多字典参数调用
create_objection('c1',{'t':1},{'whatever':[3453,3453]},{'whatever2':[34,34]}),输出完全符合你的预期:
2 {'name': 'c1', 'position': {'t': 1}, 'extra_info': [{'whatever': [3453, 3453]}, {'whatever2': [34, 34]}]}
内容的提问来源于stack exchange,提问作者JFerro
相关产品推荐
相关产品推荐

