扩展dict:通过through函数传递关键字args不需要n

2024-10-01 04:51:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试着用

dict(existing, **kwargs)

但当kwargs通过另一个函数来时,这不起作用。 有人能帮我理解为什么会这样吗

样品测试代码:

def funct(*args, **kwargs):
    a = {'a': 1, 'b': 2}
    print kwargs
    return dict(a, **kwargs)

def thrgh(*v, **var):
    print var
    funct(*v, **var)

if __name__ == '__main__':
    print 'hello world'
    print funct(c=3)
    print 'helloWorld-thrg'
    print thrgh(c=3)

输出

hello world
{'c': 3}
{'a': 1, 'c': 3, 'b': 2}
helloWorld-thrg
{'c': 3}
{'c': 3}
None

Tags: 函数helloworldvardef样品dictkwargs
1条回答
网友
1楼 · 发布于 2024-10-01 04:51:40

你只需要这个:

def funct(*args, **kwargs):
a = {'a': 1, 'b': 2}
print (args)
print (kwargs)    
return dict(a, **kwargs)

funct('t', c=1)

这将返回:

('t',)
{'c': 1}

{'a': 1, 'b': 2, 'c': 1}

相关问题 更多 >